9

The following code works:

def bbb(v: Double => Unit)(a: Double): Unit = v(a)
bbb{v: Double => v == 0 }(5)
bbb{v: Double =>  Array(v) }(5)

But if I overload bbb as follows, it doesn't work unless I manually assign the type signature for the first bbb call:

def bbb(v: Double => Unit)(a: Double): Unit = v(a)
def bbb(v: Double => Array[Double])(a: Double): Array[Double] = v(a)
bbb{v: Double => v == 0 }(5) // bbb{(v => v == 0):(Double => Unit)}(5)
bbb{v: Double =>  Array(v) }(5)
hasumedic
  • 2,139
  • 12
  • 17
宇宙人
  • 1,197
  • 3
  • 10
  • 28
  • Check this one explanation: http://stackoverflow.com/questions/4899320/when-does-scala-need-parameter-types-for-anonymous-and-expanded-functions – Nikita Aug 01 '16 at 12:55
  • @ipoteka I think the two questions are different? `v: Double => v == 0` can not apply to `def bbb(v: Double => Array[Double])` but it can apply to `def bbb(v: Double => Unit)`, doesn't it? – 宇宙人 Aug 01 '16 at 13:03

1 Answers1

6

I think this is related to implicit conversions. In the first case, when you only have a definition that results in a Unit, even though you get results such as Boolean or Array, an implicit conversion to Unit is triggered returning you always the expected Unit.

When you overload, this implicit conversion is no longer applied, but the overloading resolution mechanism instead. You can find how this works in more detail in the Scala Language Specification

hasumedic
  • 2,139
  • 12
  • 17
  • I originally think it's related with covariance. It is pretty late now, I will look at the stuff you provide tomorrow. – 宇宙人 Aug 01 '16 at 14:00
  • 2
    In particular, args are typed without an expected type, so the function literal is `Double => Boolean` instead of `Double => Unit`; if it expects `Double => Unit`, "value discarding" is what allows it and `-Ywarn-value-discard` warns about it, since it is often undesirable. – som-snytt Aug 01 '16 at 14:42
  • Thank you both, both are right. `Unit` is at the same level as `Boolean` in the type hierarchy. It is implicit conversion, specifically `value discarding`, not subtyping. – 宇宙人 Aug 02 '16 at 01:29