简体   繁体   中英

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 List[T] , for any element of type T .

What is that supposed to mean?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM