James Raitsev
James Raitsev

Reputation: 96521

Types of objects in Scala's Lists

I was under impression that every object in a Scala List must have the same type and if we need to have a collection of something of different types, tuples should be used.

From Scala's documentation, List is

A class for immutable linked lists representing ordered collections of elements of type.

scala> val l1 = List(1,2,3)
l1: List[Int] = List(1, 2, 3)

scala> val l1 = List(1,2,3, "oh really?!")
l1: List[Any] = List(1, 2, 3, oh really?!)

This does not seem to be the case. After all Any on its own is a valid Scala type and everything can be reduced to it.

Please clarify

Upvotes: 3

Views: 6802

Answers (1)

Sebastiaan van den Broek
Sebastiaan van den Broek

Reputation: 6361

You didn't specify the type of the list explicitly and you put in two types of objects, it would seem convenient that it makes this a list of type 'Any' and it doesn't break the rules. If you had said val l1: List[Int] = List(1,2,3, "oh really?!") it would have been a different case (as in: it would tell you there's a type mismatch)

It doesn't always just resolve to Any either. Consider you have a class called Vehicle and two classes inheriting from it called Bike and Car.

val car = new Car
val bike = new Bike
val vehicleList = List(car, bike)

vehicleList will now be of type Vehicle. If you had only put a Car or a Bike in there then it would have been of that specific type.

Optional background information: A List in Scala is covariant, meaning that if Int and String are subtypes of Any, then List[Int] and List[String] are also subtypes of List[Any]. This means you can have a list that contains Integers and Strings and is the reason that your statement is valid and automatically results in a List[Any]. This is not always a given fact by the way and can actually lead to trouble if the list is mutable. Luckily the default List in Scala isn't. If you want to know more, a longer explanation can be found at Covariance, Invariance and Contravariance explained in plain English?

Upvotes: 11

Related Questions