Reputation: 3180
When I define this function, I can call it without a problem:
scala> val c = (_: String) + "sd"
c: String => String = <function1>
scala> c("1")
res13: String = 1sd
However if I let the above function print
the result without returning it, I have the following error:
scala> val b = print((_: String) + "sd")
<function1>b: Unit = ()
scala> b("1")
<console>:26: error: Unit does not take parameters
b("1")
^
I know the system method print
returns Unit
type, but shouldn't the function b
be a function that can be called with an argument as I defined? Why the above b
function can not be called with b("1")
?
How to understand and solve the problem? Thank you.
Upvotes: 1
Views: 361
Reputation: 48430
Indeed, as you have already discovered
print((_: String) + "sd")
expands to
print((x: String) => x + "sd")
instead of the desired
(x: String) => print(x + "sd")
because _
binds to the innermost expression delimiter ()
or {}
.
Upvotes: 2
Reputation: 51271
Consider the following sequence.
An anonymous function from String
to String
.
scala> (_: String) + "sd"
res0: String => String = $$Lambda$1156/0x00000008406c1040@6b8bdcc6
Print the String
representation of the anonymous function.
scala> println((_: String) + "sd")
$line10.$read$$iw$$iw$$$Lambda$1158/0x00000008406c3040@31f5b923
Print the String
representation of the anonymous function. Save the result in variable b
.
scala> val b = println((_: String) + "sd")
$line11.$read$$iw$$iw$$$Lambda$1159/0x00000008406a7040@173cfb01
b: Unit = ()
The print()
and println()
passed parameter is call-by-reference, not call-by-name, so it is fully evaluated at the call site before being passed to print()
. In this case print()
receives a function, it doesn't become part of a larger function.
Upvotes: 1