I have some trouble with Scala type inference. In following worksheet example I have defined a Map which maps Any values to a function returning a Unit value.
Interestingly, when I try to define the same map using only one line of code it doesn't work because the 'bar' functions return-type suddenly changes to Any instead of Unit.
type UnitFun = (Any) => Unit
val foo = "foo"
val bar = (a: Any) => System.out.println("bar")
val map: Map[Any, UnitFun] = Map().withDefaultValue(((a: Any) => Unit))
val doesCompile: Map[Any, UnitFun] = map + (foo -> bar)
val doesNotCompile: Map[Any, UnitFun] = Map().withDefaultValue(((a: Any) => Unit)) + (foo -> bar)
I am using IDEA14 as IDE with Scala 2.11.6
It seems to me like this is a Feature/Bug of the Scala compiler, or am I missing something?
btw I've just noticed that when I use 'bar' as default value in 'doesNotCompile' like this:
val doesCompileNow: Map[Any, UnitFun] = Map().withDefaultValue(bar) + (foo -> bar)
it suddenly seems to work, I am pretty baffled right now. :D
Edit 1: @Mikolak
In this case, how does the following code works? :)
val a: Any => Unit = (a: Any) => Unit
val b: Any => Unit = (a: Any) => ()
Shouldn't both expressions be of a different type? Or is there some implicit type conversion involved?
sbt compile. - mikołak