class ClosureClass {
def printResult[T](f: => T) = {
println("choice 1")
println(f)
}
def printResult[T](f: String => T) = {
println("choice 2")
println(f("HI THERE"))
}
}
object demo {
def main(args: Array[String]) {
val cc = new ClosureClass
cc.printResult() // call 1
cc.printResult("Hi") // call 2
}
}
I play with the above code, and the result showed me. I have two questions
1) why both call 1 and call 2 go into choice 1?
2) How can I pass a parameter so that I can get into choice 2.
Thanks,
choice 1
()
choice 1
Hi
The type
=> Tmeans thatfis a call-by-name parameter. This means thatfis of typeT, and the expression passed into the function will be evaluated when it is used (not when the function is called.The type
String => Tmeans thatfis aFunction[String,T], that is, a function from aStringto aT.When you call with
"Hi", aStringas the argument, Scala sees that there are two choices forprintResult:1)
=> T: In this case caseTwould bind toString, which is fine.2)
String => T: This does not work sinceStringis not a function fromStringto anything… it’s not a function at all.How you fix this depends on what you are trying to do. If you just want to fix how
printResultis being called, then you call call it with:which prints:
since you are now are now correctly passing a function,
g, fromStringto someT. ThatThere isString, since the function is just adding***onto the end of whatever it is passed and returning the modified string.