scala> // An Anonymous function is a Function Literal if the function scala> // body ends up with a single statement (here in our case x.split(" ") scala> scala> // WAYS to define a Function Literal scala> val inputList = List("This is a string", "This is also a string") inputList: List[String] = List(This is a string, This is also a string) scala> scala> // Way 1 : Assign the Function Literal to a variable(This is different scala> // from using 'def' to define a Named Function) scala> val fn1:String => Array[String] = x => x.split(" ") fn1: String => Array[String] = <function1> scala> val result = inputList.map(fn1) result: List[Array[String]] = List(Array(This, is, a, string), Array(This, is, also, a, string)) scala> scala> // Way 2 : Use Function1, Function2, etc... scala> val fn1:Function1[String, Array[String]] = x => x.split(" ") fn1: String => Array[String] = <function1> scala> val result = inputList.map(fn1) result: List[Array[String]] = List(Array(This, is, a, string), Array(This, is, also, a, string)) scala> scala> // Way 3 : Pass the Function Literal Directly as Argument scala> val result = inputList.map( x => x.split(" ")) result: List[Array[String]] = List(Array(This, is, a, string), Array(This, is, also, a, string))
Function Literal : Ways to define Function Literal
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment