Dato un semplice algebrica dati Tipo di Parent
:Trait Comportamento imprevisto
scala> sealed trait Parent
defined trait Parent
scala> case object Boy extends Parent
defined object Boy
scala> case object Girl extends Parent
defined object Girl
ho definito un tratto:
scala> trait HasGirl {
| val x: Girl.type
| }
defined trait HasGirl
Poi, ho creato una classe case che ha implementato HasGirl
, ma fornito un valore x
di Boy.type
.
scala> case class Thing(x: Boy.type) extends HasGirl
defined class Thing
mi aspettavo un errore di compilazione, dal momento che non vedo come un x
di tipo Boy.type
conforme alle val x: Girl.type
.
Cosa sta succedendo qui?
È il 'x' in' Thing' relativo al 'x' nel tratto? –
Bene, "Cosa" estende "HasGirl". Dato che quest'ultimo si aspetta un 'x' di tipo' Girl.type', io * credo * che 'Thing'' x: Boy.type' sia mappato a 'HasGirl''s' x'. –
Infatti, 'Thing (Boy) .asInstanceOf [HasGirl] .x' produce' java.lang.ClassCastException: Boy $ non può essere lanciato su Girl $ '. Interessante. – ale64bit