Nan Xiao
Nan Xiao

Reputation: 17467

Why passing different function types in called-by-name function still work?

In Scala, defining a function whose parameter is called by name is like this:

def f(x: => R)

I think => R means the a function whose parameters are empty and return value type is R. But when I pass a function whose type is not => R into f, such as R => R, I find it still works. The example is like this:

scala> def foo(code: => Int) {
     | println(code)
     | }
foo: (code: => Int)Unit

scala> val bar: () => Int = () => 1
bar: () => Int = <function0>

scala> foo(bar())
1

scala> val bar1: Int => Int = myInt => 2
bar1: Int => Int = <function1>

scala> foo(bar1(2))
2

Could anyone can explain it?

Upvotes: 0

Views: 60

Answers (1)

Denis Rosca
Denis Rosca

Reputation: 3459

The x: => R in the function definition doesn't stand for function without parameters which returns R, but it means an expression which, when evaluated, returns a value of type R without specifying anything else about the expression itself.

Upvotes: 2

Related Questions