Tuesday, September 20, 2016

Using Curly Braces for Function Calls...

scala> //Any method that has only 1 argument can be called #213

scala> // using Curly braces instead of Parenthesis

scala> //The real utility of Curly Braces comes into Picture

scala> // when we being to pass Function Literals as argument

scala> // to a Function

scala>

scala> //The method

scala> def demo(msg: String) = {
     |    println("Message -> " + msg)
     | }
demo: (msg: String)Unit

scala>

scala> //Example 1 : Called using parenthesis

scala> demo("hello")
Message -> hello

scala>

scala> //Example 2 : Called using Curly Braces

scala> demo{"hello"}
Message -> hello

scala>

scala> //-------------------------------------------

scala> //NOTE : Functions with 2 arguments cannot be

scala> //called in this way(as shown below). We would

scala> //need to use 'Currying' in order to achieve

scala> //this

scala> //-------------------------------------------

scala> def printMsg(msg1: String, msg2: String) = {
     |    println("M1 -> " + msg1 + ", M2 -> " + msg2)
     | }
printMsg: (msg1: String, msg2: String)Unit

scala>

scala> //This works

scala> printMsg("hello", "scala")
M1 -> hello, M2 -> scala

scala>

scala> //This do not work

scala> printMsg{"hello", "scala"}
<console>:1: error: ';' expected but ',' found.
       printMsg{"hello", "scala"}
                       ^