What’s the difference of the following definition?
1.def debug(msg: => AnyRef) = { println(String.valueOf(msg)) }
2.def debug(msg: () => AnyRef) = { println(String.valueOf(msg)) }
The first definition can accept any thing, string, or function etc. but the second one can only accept function. I’d like to know reazon.
scala> def debug(msg: => AnyRef) = { println(String.valueOf(msg)) }
debug: (msg: => AnyRef)Unit
scala> debug("hi")
hi
scala> debug(() => "xx")
<function0>
scala> def debug(msg: () => AnyRef) = { println(String.valueOf(msg)) }
debug: (msg: () => AnyRef)Unit
scala> debug("hi")
<console>:9: error: type mismatch;
found : java.lang.String("hi")
required: () => AnyRef
debug("hi")
^
The first is a call-by-name parameter, i.e. it evaluates the the argument each time it is used in the method, and only if it is used. As you have discovered, this can be anthing that evaluates to the required type.
The second takes specifically a
Function0[AnyRef]object. You can think of the()as an empty parameter list (not to be confused with theUnitvalue, which is written the same).