in short: () ⇒ String
creates a function of type Unit ⇒ String
while ⇒ String
means lazy value of type String
is passed as an argument, hence it is not re-evaluated later in the function body, if referenced.
So it will be evaluated only once when execution reaches it's reference in the code, and not when passed as an argument.
This form is very common for creation of high-order functions that accept somebody, like:
def func(f: ⇒ String) : Either[Exception, String]{
if (someCondition) {
Right(f)
} else {
Left(new IllegalArgumentException("F can't be evaluated")
}
}
And the possible usage is:
def doF() {
func {
io.Stream.fromFile("path/to/file")
}
}
ofcourse you could rewrite this as follows:
def func(f: () ⇒ String) : Either[Exception, String]{
if (someCondition) {
Right(f())
} else {
Left(new IllegalArgumentException("F can't be evaluated")
}
}
And the possible usage is:
def doF() {
func {
case _ ⇒ io.Stream.fromFile("path/to/file")
}
}
Depending on the context, you may choose former or latter form, those are completely interchangable in the cases described above. The only difference is that if you pass a lazy value to the function - it will be evaluated only once, but if you pass the function reference to the function - the function will be executed and the result of the evaluation passed to the function as many times as it is used in the function.