Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass function argument as code block

Tags:

scala

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?

like image 345
jfisher Avatar asked May 04 '13 08:05

jfisher


2 Answers

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"}

like image 63
4lex1v Avatar answered Sep 19 '22 10:09

4lex1v


bar accepts a function that takes no arguments and returns String. You gave it just a String. To make it work:

bar{() => "xyz"}
like image 29
ghik Avatar answered Sep 22 '22 10:09

ghik