I am new to Scala. I have been searching but there is no easy "search string" for the seemingly easy question I have.
def foo( f: (String) => String ){println(f("123"))}
foo{_+"abc"} //works
def bar( f :() => String ){println(f())}
bar{"xyz"} // why does this not work?
def baz( f: => String ){println(f)}
baz{"xyz"} //works
Why does the second (bar
) not work?
Second baz
works because it's not a function literal, but a call-by-name parameter. Basically what it does is delaying the moment of argument computation until it's needed in the program. You can also read about this in this question.
As for bar
you just need to pass a function like bar{() => "xyz"}
bar
accepts a function that takes no arguments and returns String
. You gave it just a String
. To make it work:
bar{() => "xyz"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With