If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Wednesday, July 10, 2013

Understanding Functions in Scala

/**
Functions are first class citizens in Scala and a function that takes a single argument
obeys below interface (trait in scala). It should have a method called apply which takes
an argument of type T1 and returns a value of type R.
**/
trait Function1[-T1, +R] extends AnyRef { self =>
/** Apply the body of this function to the argument.
* @return the result of function application.
*/
def apply(v1: T1): R
}
/**
In Scala there are 2 ways to indicate that a class implements a function Trait:
[1] extends Function1[Int,Int]
[2] extends (Int => Int)
You can also write a function using the def keyword
**/
object FuncFun {
class DoubleFunction extends (Int => Int) {
def apply(x:Int): Int = x * 2
}
def timesFour(x: Int): Int = x * 4
def doSomethingWithNumber(x: Int, f: Int => Int): Int = f(x)
def main(args: Array[String]): Unit = {
//this will print 6
println(doSomethingWithNumber(3, new DoubleFunction()))
//this will print 8
println(doSomethingWithNumber(2, timesFour))
}
}
view raw gistfile1.scala hosted with ❤ by GitHub

No comments:

Post a Comment