When type bounds exist on a type parameter, how exactly does Scala determine the type to infer? For example:
def onMouseClicked_=[T >: MouseEvent](lambda: T => Unit) =
setOnMouseClicked(new EventHandler[T] {
override def handle(event: T): Unit = lambda(event)
})
When attempting to use this function, such as in:
onMouseClicked = { me => doSomething() }
me
will have the inferred type of MouseEvent
. The type bound of T
is a lower type bound, so T
must either be of type MouseEvent
or a supertype of MouseEvent
, so why does me
have the inferred type of MouseEvent
? Shouldn't it infer the most general type?
Is it something I'm not getting about how Scala's type inference works? Or is my understanding of type bounds completely wrong?
Edit:
Let's say we further restrict the the type of T to be a subtype of Event
, where Event
is a supertype of MouseEvent
. So we get:
def onMouseClicked_=[T >: MouseEvent <: Event](lambda: T => Unit) =
setOnMouseClicked(new EventHandler[T] {
override def handle(event: T): Unit = lambda(event)
})
So if we do
onMouseClicked = { me: MouseDragEvent => doSomething() }
where MouseDragEvent
is a subtype of MouseEvent
, the compile fails with a type error, as expected, because the bound ensures that me
must be a supertype of MouseEvent
.
And yet if we do
onMouseClicked = { me: Any => doSomething() }
the compile succeeds. It's obvious that Any
is not a subtype of Event
, so why does the compile succeed? What is inferred type of T
?
Any => Unit
, how isT
inferred then? – Daphne