Am 09.09.2012 um 15:49 schrieb Cecil Westerhof <
cldwes...@gmail.com>:
> Op zondag 9 sep 2012 15:11 CEST schreef AGYNAMIX Torsten Uhlmann:
>
>> Glad I could help.
>>
>> Now when you use param: => String its a call-by-name parameter which is
>> evaluated each time it is accessed,
>>
>> if you use ()=>String then it's a function that gets no input parameter and
>> returns a String.
>
> I used the previous version, but the function was just called as I
> wanted. Why (if at all) should I switch to this notation?
The different notations are for different purposes. A call-by-name parameter is a parameter to a function that's evaluated on every access.
If you write a log method for instance, these parameters come in handy:
def log(msg: => String): Unit = {
if (isLogEnabled) println(msg)
}
If you call it like log("%s has the value of %s".format(valueA, valueB)) then the string is only assembled if "isLogEnabled" is true.
The other notation ()=>String is for passing blocks of code (functions) into objects, classes, methods, etc. You can pass parameters:
String=>String for instance which you can not do with a call-by-name parameter.
Now, I would guess, that a call-by-name parameter and a function with no parameters will both be compiled into a Function0 (that's a Trait that has an apply method that returns what your function would return or what your parameter type is), but I don't know if there are internal differences.
So using call-by-name conveys a different message than using a function block.
Here's an example with a function that takes a parameter:
scala> def uuid(prefix: String)={
| println("Getting uuid")
| prefix+java.util.UUID.randomUUID
| }
uuid: (prefix: String)java.lang.String
scala> def delayed(prefix: String, func: String=>String)={
| println("In delayed method")
| func(prefix)
| }
delayed: (prefix: String, func: String => String)String
scala> delayed("Hi_", uuid)
In delayed method
Getting uuid
res1: String = Hi_d40649f1-c417-43dd-87e4-35bd2121fc47
Hope I could clear up the head spinning :)
Torsten.