Skip to content
Search

Scala:CompoundTypes

lastmod 2020-09-11created 2020-09-111 edits

Sometimes it is necessary to express that the type of an object is a subtype of several other types. In Scala this can be expressed with compound types, which are intersections of object types.

About

Consider two traits, Cloneable and Resetable:

trait Cloneable extends java.lang.Cloneable {
  override def clone(): Cloneable = { 
    super.clone().asInstanceOf[Cloneable]
  }
}
trait Resetable {
  def reset: Unit
}

Now suppose we want to write a function cloneAndReset that takes an object as a parameter, clones it, and resets the original object:

def cloneAndReset(obj: ?): Cloneable = {
  val cloned = obj.clone()
  obj.reset
  cloned
}

The question arises what the type of the parameter obj is.

  • If it is Clonable, the object can be cloned (clone) but not reset (reset).
  • If, on the other hand, it is Resetable, the object can be reset (reset), but the clone operation is not available.

To avoid type casting in such a situation, we can specify both types, Clonable and Resetable.

This compound type is written in Scala as follows:

ClonablewithResetable

Rewriting the function above gives:

def cloneAndReset(obj: Cloneable with Resetable): Cloneable = {
  //...
}

Compound types can consist of several object types, and they may have a single refinement which can be used to narrow the signature of existing object members. The general form is A with B with C ... { 리파인먼트 }.

See also

Favorite site

author Zer0 sitemap