user3663882 user3663882 - 1 year ago 65
Scala Question

How does generic type work in Scala?

I was very surprised by the fact that we can assign List[Nothing] To any list. Like this

val nums : List[Number] = List(1, 2, 3, 4)
val nums_2 : List[Integer] = Nil; // <--- extends List[Nothing]
val ints : List[Integer] = nums // error: type mismatch

So, this is very confusing. In this article they said that

Because lists are covariant in Scala, this makes
scala.collection.immutable.Nil an instance of
, for any element
of type

What is that supposed to mean?

Answer Source

If a generic type is covariant in a given type parameter (denoted by a + before that type parameter in the type's definition, like abstract class List[+T]), that means that if you have two types T and U, such that T is a subtype of U, List[T] is also a subtype of List[U].

So a variable that's supposed to hold a List[Any] can also hold a List[String] because String is a subtype of Any and a variable that's supposed to hold a List[Whatever] can also hold a List[Nothing] because Nothing is a subtype of every type (it's kinda magical in that regard).