Why is this illegal:
def foobar() = {}
val option: Option[() => Unit] = Some(foobar)
Whereas this is legal:
def foobar() = {}
val intermediate: () => Unit = foobar
val option: Option[() => Unit] = Some(intermediate)
In the first example, the compiler complains that the right side of the assignment is of type Option[Unit]
rather than Option[() => Unit]
.
I suspect this has something do with foobar
being evaluated rather than being passed as a variable to Some()
, but I'm unsure.
It's because parentheses are optional when evaluating an empty-parens method. By convention, they're left off for pure methods, but that's just convention. So you're right, it's actually evaluating foobar instead of eta-expanding it to a function. You can fix your first example by explicitly invoking eta expansion with the underscore operator:
val option: Option[() => Unit] = Some(foobar _)
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