user7938511 user7938511 - 1 month ago 7
Scala Question

Scala List: Why does this List operation work?

given that the full signature of :: is as follows

::[B >: A](x: B): List[B
]

then why does this example work?

class Fruit(name: String) { }
class Orange(name: String) extends Fruit(name)
class BigOrange(name:String) extends Orange(name)

val f = new Fruit("fruit")
val a = new Apple("apple")
val o = new Orange("orange")
val bo = new BigOrange("big orange")

val oList :List[Orange] = List[Orange](o,o)
val fList1: List[Fruit] = f::oList
val fList2: List[Fruit] = a::oList
val oList2 :List[Orange] = bo::oList // works, but why?


all works and compiles...but why does the last line even work? Does'nt the signature above say that it only works if supertype of orange is appended?

I get it that a BigOrange is an Orange, so it would seem to make intuitive sense that a list of oranges is able to add a BigOrange. But the signature: it explicitly seems to disallow that operation

Answer Source

<: and >: are reflexive, that is every type is a sub and supertype of itself.

So introducing B >: A as the type of the prepended item does not disallow values of type A.