Sunday, September 18, 2016

Function Literal, Function Value, Placeholder Syntax : Example...

scala> // Function Literal Example #183

scala> val input = List(1, 2, 3, 4)
input: List[Int] = List(1, 2, 3, 4)

scala>

scala> //Way 1 : Assigning the function literal to a function value

scala> //f1 : Function value      : Functional values are instances

scala> //(x:iInt, y:Int) => x + y : Function Literal(Is simply a

scala> //                           definition...Similar to class)

scala> val f1 = (x:Int, y:Int ) => x + y
f1: (Int, Int) => Int = <function2>

scala> input.reduce(f1)
res108: Int = 10

scala>

scala> //Way 2 : Passing function Literal directly

scala> input.reduce((x:Int, y:Int) => x + y)
res109: Int = 10

scala>

scala> //Way 3 : Skipping the type information

scala> //This is acheived through 'Target Typing' #186

scala> input.reduce((x, y) => x + y)
res110: Int = 10

scala>

scala> //Way 4 : Using Placeholder syntax #186

scala> //Can be used when we use the arguments only once

scala> //in the function literal

scala> //Note here... first '_' refers the First Parameter

scala> //             and the second '_' refers the Second

scala> //             Parameter

scala> input.reduce(_ + _)
res111: Int = 10

scala>

scala> //Way 4 : Another example using Placeholder Syntax

scala> input.foreach(println(_))
1
2
3
4

scala>

scala>

scala> //Way 5 : Omitting Placeholder

scala> //This only works for Single arument Function Literal

scala> input.foreach(println)
1
2
3
4