Tuesday, April 3, 2012

Scala Basics - Anonymous Functions

Simple way to create anonymous functions on Scala

scala> (result: String) => "Hello " + result
res0: String => java.lang.String = <function1>
It adds "Hello" to an String result, so we call this function like this
scala> res0("Scala")
res2: java.lang.String = Hello Scala

Pass anonymous functions into vals
scala> val welcome = (result: String) => "Hello " + result
welcome: String => java.lang.String = <function1>

scala> welcome("Scala")
res3: java.lang.String = Hello Scala

Expressions - {}
You can define expressions like this
scala> def welcome(message: String): String = {
    "Hello " + message
}
welcome: (message: String)String

scala> welcome("world")
res4: String = Hello world


scala> def addition(i: Int): Int = {
     i + 10
}

Real anonymous function
scala> { message: String =>
       "Hello " + message
 }
res5: String => java.lang.String = <function1>
scala> res5("Anonymous function")
res6: String = Hello Anonymous function

No comments:

Post a Comment