2015-11-28 22 views
18

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?

+0

È il 'x' in' Thing' relativo al 'x' nel tratto? –

+0

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'. –

+2

Infatti, 'Thing (Boy) .asInstanceOf [HasGirl] .x' produce' java.lang.ClassCastException: Boy $ non può essere lanciato su Girl $ '. Interessante. – ale64bit

risposta

1

Sembra che i tipi singleton senza membri siano equivalenti di tipo in qualche modo qui. Forse è un bug (hai archiviato un biglietto). Ad esempio, il seguente produce un runtime-error:

sealed trait Parent 
case object Boy extends Parent 
case object Girl extends Parent 

trait HasGirl { 
    val x: Girl.type 
} 

case class Thing(x: Boy.type) extends HasGirl { 
    def y: Girl.type = (this: HasGirl).x 
} 


val t = Thing(Boy) 
t.y // ClassCastException ! 

Se posso aggiungere un membro, si ottiene un errore di compilazione:

sealed trait Parent 
case object Boy extends Parent 
case object Girl extends Parent { def hello = 1234 } 

trait HasGirl { 
    val x: Girl.type 
} 

case class Thing(x: Boy.type) extends HasGirl 
<console>:57: error: overriding value x in trait HasGirl of type Girl.type; 
value x has incompatible type 
     case class Thing(x: Boy.type) extends HasGirl 
         ^
+0

Si tratta di un bug, per https://issues.scala-lang.org/browse/SI-9574 –

Problemi correlati