Functions in Scala
November 26, 2019 Leave a comment
As scala is functional programming we will be able to use functions as first class citizens (passing functions as arguments, returning functions as return type, assigning functions to variables…)
But the problem is that scala sits on top of JVM and JVM is designed for Object Oriented Programming. Scala solves this problem like this
trait MyFunction[A, B] { def apply(element: A): B } // Java way of implementing above function aka Anonymous Function val doubler = new MyFunction[Int, Int] { // does not need 'override keyword for trait methods' def apply(e: Int): Int = e * 2 } println(doubler(5)) // prints 10
For this reason, to enable developers make use of functional programming concepts, scala provided pre-defined traits/functions (Function1 till Function22) that can take up to 22 generic parameters.
Function1 takes 1 type as input (input param) and return 1 type as output (return type). For example, we can redefine above implementation like this
val scalaDoubler = new Function1[Int, Int] { def apply(a: Int) = a * 2 } println("Scala Doubler: "+scalaDoubler(5))
Apply Method: This method is very special and allows us to call instances of classes or singleton objects like they were functions. And functions are actually instances of classes with apply method.
Anonymous Functions
In scala we can write anonymous function as LAMBDA.
Same Function1 above can be re-written as below different ways
val scalaDoubler1 = (a: Int) => a * 2 or val scalaDoubler1: (Int => Int) = a => a * 2 or val scalaDoubler1: (Int => Int) = _ * 2 println(scalaDoubler1(5))
Recent Comments