10.5. Declaring a Type When Creating a Collection

Problem

You want to create a collection of mixed types, and Scala isn’t automatically assigning the type you want.

Solution

In the following example, if you don’t specify a type, Scala automatically assigns a type of Double to the list:

scala> val x = List(1, 2.0, 33D, 400L)
x: List[Double] = List(1.0, 2.0, 33.0, 400.0)

If you’d rather have the collection be of type AnyVal or Number, specify the type in brackets before your collection declaration:

scala> val x = List[Number](1, 2.0, 33D, 400L)
x: List[java.lang.Number] = List(1, 2.0, 33.0, 400)

scala> val x = List[AnyVal](1, 2.0, 33D, 400L)
x: List[AnyVal] = List(1, 2.0, 33.0, 400)

Discussion

By manually specifying a type, in this case Number, you control the collection type. This is useful any time a list contains mixed types or multiple levels of inheritance. For instance, given this type hierarchy:

trait Animal
trait FurryAnimal extends Animal
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal

create a sequence with a Dog and a Cat:

scala> val x = Array(Dog("Fido"), Cat("Felix"))
x: Array[Product with Serializable with Animal] = Array(Dog(Fido), Cat(Felix))

As shown, Scala assigns a type of Product with Serializable with Animal. If you just want an Array[Animal], manually specify the desired type:

scala> val x = Array[Animal](Dog("Fido"), Cat("Felix"))
x: Array[Animal] = Array(Dog(Fido), Cat(Felix))

This may not seem like a big deal, but imagine declaring ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.