Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Higher order functions that don't take any parameters being resolved

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.

like image 861
letsgoyeti Avatar asked Dec 15 '22 20:12

letsgoyeti


1 Answers

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 _)
like image 196
acjay Avatar answered Apr 30 '23 07:04

acjay