Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a function literal used as a default argument require a parameter type?

This compiles fine:

def walk[X](a: X)(f: X => Boolean): Boolean =  f(a)

walk(1)(_ => true)

This compiles fine as well:

def walk(a: Int)(f: Int => Boolean = _ => true): Boolean =  f(a)

walk(1)()

This does not:

def walk[X](a: X)(f: X => Boolean = _ => true): Boolean = f(a)

walk(1)()

The error is:

Error:(1, 38) missing parameter type

The obvious workaround is to use (_: X) => true, but why is this an error? I though that when the second parameter list is being processed, type information obtained from the first one should already be available?

Tested with Scala 2.11.8 and 2.12.1

like image 487
Suma Avatar asked Apr 05 '26 19:04

Suma


1 Answers

Looks like this issue. Note that this is the case only for default parameters; elsewhere the inference works just fine.

For example,

// works
def walk1[X]: X => Boolean = _ => true

// fails
def walk2[X](f: X => Boolean = _ => true) = ???
like image 81
slouc Avatar answered Apr 08 '26 13:04

slouc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!