This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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)) | |
} | |
} |
No comments:
Post a Comment