Last active
December 24, 2015 21:39
-
-
Save kevinlynx/6867672 to your computer and use it in GitHub Desktop.
function literal in scala
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
object Test2 { | |
//Also: def callFn(a: Int, f: (Int) => Int) = { | |
def callFn(a: Int, f: Int => Int) = { | |
a + f(a) | |
} | |
// 2 parameters | |
def callFnMult(a: Int, f: (Int, Int) => Int) = { | |
a + f(a, a) | |
} | |
// A curry function | |
def callFnCurry(a: Int, f: Int => Int => Int) = { | |
a + f(a)(a) | |
} | |
def callCurryFn(a: Int)(f: Int => Int => Int) = { | |
a + f(a)(a) | |
} | |
// Damn... | |
def callByName(a: Int)(f : => Int => Int => Int) = { | |
a + f(a)(a) | |
} | |
def main(args: Array[String]) { | |
def fn(a: Int) = 1 | |
println(callFn(2, fn)) | |
// worked | |
println(callFn(2, fn _)) | |
println(callFn(3, A => 3)) | |
println(callFn(3, { A => 3 })) | |
println(callFnMult(4, { (A, B) => A + B })) | |
// Arg1 => Arg2 => Ret | |
println(callFnCurry(4, { A => B => A + B })) | |
// worked | |
println(callFnCurry(4, A => B => A + B)) | |
println(callCurryFn(4) { A => B => A + B }) | |
println(callCurryFn(4) (A => B => A + B )) | |
println(callByName(4) { A => B => A + B }) | |
// `{' and `(' mean nothing here, they just return the last expression value, and | |
// the compiler will infer type for `a', that's why we can define a function literal by | |
// callCurryFn(4) { A => B => A + B } // or | |
// callCurryFn(4) (A => B => A + B ) | |
val a = { "hello"; 1 } + (2) + { 3 } | |
println(a.getClass) | |
// define a function: String => Unit | |
// `s' will be a tuple | |
val b: (String, Int) => Unit = { case s => println(s.getClass()) } | |
b("unit function", 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment