Another Tour of Scala

TypeBounds

The Gist

Upper Bounds and Lower Bounds describe Scala’s support for restricting the types that can be used in a genericized class

My Interpretation

Just as with Java, in Scala you can put bounds on the generic types allowed to a generic class or method.

Suppose we have an object hierarchy of entities. We have a root entity that all must extend, and then a special secondary entity for reference data (data that is a code and a description and only aggregated by other entities).

Further, we wish to define a sorting class that we can apply to all reference data.

We could have created the sorter class to just take ReferenceData, but the regular and sorted methods would not return properly typed Lists, they would return lists of ReferenceData and not, say List[Gender], which would be more useful.

This is essentially the same concept as List<T extends Foo> that you have in java, though more concise.

You can also bound the other way, via List[T >: Foo]

My Thoughts on this Feature

Here we are going down the rabbit hole of static typing. I have found many uses for upper bounds, and almost no uses for lower bounds in Java, but I find the Scala syntax quite unpleasant. Even though it’s a few more characters, to me <T extends Foo> is just much clearer and easier to remember than [T <: Foo]. I instantly knew what the Java version meant, but still have to look up which syntax to use for Scala.

Like ScalaGenerics , you really do have to have this feature, but this is where the static types start to get confusing and muddle intent, IMO.