Sunday, August 28, 2016

Function Literal

A Function Literal is a function which do not have Name(#74)

val greetings=Seq("hello", "world")
greetings.foreach(x => println(x))

/*If the argument of the Functional Literal is specified an explicity 
type, then in should be wrapped in Parantheses #75*/
greetings.foreach(x:String=> println(x))
greetings.foreach((x:String)=> println(x))

/*If a function literal takes only 1 statement
and the statements only takes one argument,
then we can omit the argument #75 */
greetings.foreach(println) 
scala> val greetings=Seq("hello", "world")
greetings: Seq[String] = List(hello, world)
//Here x => println(x) is a Function that 
//do not have Name
scala> greetings.foreach(x => println(x))
hello
world

scala> 

scala> /*If the argument of the Functional Literal is specified an explicit 
     | type, then it should be wrapped in Parantheses #75*/
     | greetings.foreach(x:String=> println(x))
<console>:3: error: ')' expected but '(' found.
       greetings.foreach(x:String=> println(x))
                                           ^
<console>:3: error: ';' expected but ')' found.
       greetings.foreach(x:String=> println(x))
                                              ^

scala> greetings.foreach((x:String)=> println(x))
hello
world

scala> 

scala> /*If a function literal takes only 1 statement
     | and the statements only takes one argument,
     | then we can omit the argument #75 */
     | greetings.foreach(println) 
hello
world