Custom Syntax

During those workshops you will learn how to create custom syntax in scala which looks like part of the language itself. This technique is used in many scala based frameworks.

DEMO

FILE : CustomConstructionsDemo.scala

CODE EVOLUTION

Simple Function

val addOne:Int=>Int = i => i+1

Simple Method

def add(a:Int,b:Int):Int = a+b

Method with multiple parameters groups

def add2(a:Int)(b:Int) = a+b

Method with Multiple parameters group with function as a param

def invokef(a:Int,f:Int=>Int) = f(a)

Custom construction

def invokef2(a:Int)(f:Int=>Int) = f(a)

//invocation
invokef2(3)((i:Int)=>i*2)
invokef2(3)({(i:Int)=>i*2})
invokef2(3){(i:Int)=>i*2}

invokef2(3){(i:Int)=>
      i*2
}

Loan Pattern

Custom constructions allow us to use loan pattern where we can split management of resource lifecycle from pure operations on this resource.

with(filePath){fileStream =>
      standard function body easy to test
}

FILE : CustomConstructionsExerciseSpec.scala

Loan pattern in tests:

 def withConnection(testCode: CustomConnection => Any): Unit = {
    val conn = new CustomConnection(List("test1", "test2"))
    try {
      conn.open()
      testCode(conn)
    } finally {
      conn.close()
    }
  }


  "Custom connection" should "be provided " in withConnection{conn=>
    conn.query("customQuery") should contain allOf("test1","test2")  
  }

EXERCISES

in test package FILE : CustomConstructionsExerciseSpec.scala

  • better explain compose twice
  • better explain withMap
  • not in customWhile that it has to be implemented with if

results matching ""

    No results matching ""