What are compound types in Scala?

In Scala, the term compound type refers to an object whose type is a subtype of multiple types or the intersection of multiple object types.

Suppose that we have two traits: Vehicle and Car.

trait Vehicle extends java.lang.Vehicle {
override def clone(): Vehicle = {
super.clone().asInstanceOf[Vehicle]
}
}
trait Car {
def set: Unit
}

We can also write another function named vehicleAndCar which takes an object, clones it, and then resets the original object.

def vehicleAndCar(obj: ?): Vehicle = {
val cloned = obj.clone()
obj.reset
cloned
}

Now, we have to clarify the type of the parameter obj. If it is Vehicle, then the object can be cloned, but we cannot reset it. If it is Car, we can reset it, but cannot perform the clone operation.

To avoid these kinds of type casts, we can specify the type of obj to be both Vehicle and Car. This should be written like this: Vehicle with Car.

Here’s the updated function:

def vehicleAndCar(obj: Vehicle with Car): Vehicle = {
//...
}
Copyright ©2024 Educative, Inc. All rights reserved