Compound Types: Definition Compound Types

Definition Compound Types

trait Cloneable extends java.lang.Cloneable {
  override def clone(): Cloneable = {
    super.clone().asInstanceOf[Cloneable]
  }
}
trait Resetable {
  def reset: Unit
}
def cloneAndReset(obj: ?): Cloneable = {
  val cloned = obj.clone()
  obj.reset
  cloned
}
def cloneAndReset(obj: Cloneable with Resetable): Cloneable = {
  //...
}

Suppose we have two traits Cloneable and Resetable. Now suppose we want to write a function cloneAndReset which takes an object, clones it and resets the original object.

The question arises what the type of the parameter obj is. If it’s Cloneable then the object can be cloned, but not reset; if it’s Resetable we can reset it, but there is no clone operation. To avoid type casts in such a situation, we can specify the type of obj to be both Cloneable and Resetable. This compound type is written like this in Scala: Cloneable with Resetable. Here’s the updated function.

Related concepts

Definition Compound Types

Compound Types: Definition Compound Types — Structure map

Clickable & Draggable!

Compound Types: Definition Compound Types — Related pages: