Lambda functions in Scala

Scala supports fuctions as first class values therefore bringing the fuctional world closer to the imperative system we are so used to in Java.

Thus in scala it is possible to associate generic functions to variables using the => symbol, delivering a more mathematical touch with this so called lambda function in-language construct.

scala> val f = (x:String) => x.toBoolean
f: (String) => Boolean = <function1>

scala> f("false")
res58: Boolean = false

scala> f("true")
res59: Boolean = true

scala> f("tru")
java.lang.NumberFormatException: For input string: "tru"
	at scala.collection.immutable.StringLike$class.parseBoolean(StringLike.scala:240)
	at scala.collection.immutable.StringLike$class.toBoolean(StringLike.scala:228)
	at scala.collection.immutable.StringOps.toBoolean(StringOps.scala:31)

I love this beautiful formation that reminds me of the way we defined mathematical functions in university.

In the above example function f is itself an instance living on its own without the need of an enclosing class that takes as an argument a String and gives back a Boolean object based on the string provided. Of course we get a runtime error when passing a non-boolean String into the function.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s