Scala's function as parameter usage

functional-programming, scala

Solution

The type `=> T` means that `f` is a call-by-name parameter. This means that `f` is of type `T`, and the expression passed into the function will be evaluated when it is used (not when the function is called.

The type `String => T` means that `f` is a `Function[String,T]`, that is, a function from a `String` to a `T`.

When you call with `"Hi"`, a `String` as the argument, Scala sees that there are two choices for `printResult`:

1) `=> T`: In this case case `T` would bind to `String`, which is fine.

2) `String => T`: This does not work since `String` is not a function from `String` to 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 `printResult` is being called, then you call call it with:

val g: (String => String) = (s: String) => s + "***"
cc.printResult(g)

which prints:

choice 2
HI THERE***

since you are now are now correctly passing a function, `g`, from `String` to some `T`. That `T` here is `String`, since the function is just adding `***` onto the end of whatever it is passed and returning the modified string.

Problem

``` 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 ```

Original source