Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redundant parameter type info in partially applied function definition

Tags:

scala

def foo(num:Int, str:String):Int = 1

val bar = foo(3, _)  // compiler complains "missing parameter type for expanded function ((x$1) => test(3, x$1))"

val baz = foo(3, _:String) // compiles fine

Why do I have to explicitly specify the type of _ when it looks inferrable from the context?

EDIT: Renamed to avoid name collision following David Soergel's suggest.

like image 596
xiefei Avatar asked Dec 18 '11 02:12

xiefei


1 Answers

First of all, to avoid confusion between "def test" and "val test", let's write:

def foo(num:Int, str:String):Int = 1

val bar = foo(3, _)  // compiler complains "missing parameter type for expanded function ((x$1) => foo(3, x$1))"

val baz = foo(3, _:String) // compiles fine

What's inferrable from context is only that the argument to bar must somehow be convertible to a String. That could be due to inheritance (if instead of String you use some non-final type there), or due to an implicit conversion.

Basically the potential for implicits means that the argument to bar could be just about any type at all, so the code as written is indeed underspecified. I don't know whether the compiler actually checks whether there are any appropriate implicit conversions in scope before issuing the "missing type" error, but I would guess not. (In the case of String there are likely to be a bunch present, anyway). It would be brittle and confusing if the signature of baz changed as a result of importing a new implicit that could produce a String.

like image 137
David Soergel Avatar answered Oct 04 '22 00:10

David Soergel