O'Reilly logo

Programming Scala by Alex Payne, Dean Wampler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Type Bounds

When defining a parameterized type or method, it may be necessary to specify bounds on the type. For example, a parameterized type might assume that a particular type parameter contains certain methods.

Upper Type Bounds

Consider the overloaded apply methods in object scala.Array that create new arrays. There are optimized implementations for each of the AnyVal types. There is another implementation of apply that is parameterized for any type that is a subtype of AnyRef. Here is the implementation in Scala version 2.7.5:

object Array {
  ...
  def apply[A <: AnyRef](xs: A*): Array[A] = {
    val array = new Array[A](xs.length)
    var i = 0
    for (x <- xs.elements) { array(i) = x; i += 1 }
    array
  }
  ...
}

The type parameter A <: AnyRef means “any type A that is a subtype of AnyRef.” Note that a type is always a subtype and a supertype of itself, so A could also equal AnyRef. So the <: operator indicates that the type to the left must be derived from the type to the right, or that they must be the same type. As we said in Reserved Words, this operator is actually a reserved word in the language.

These bounds are called upper type bounds, following the de facto convention that diagrams of type hierarchies put subtypes below their supertypes. We followed this convention in the diagram shown in The Scala Type Hierarchy.

Without the bound in this case, i.e., if the signature were def apply[A](xs: A*): Array[A], the declaration would be ambiguous with the other apply methods for each of the

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required