Type Bounds
Viewing old version 88f53812270e02ea3d0c603f75da9275daf3150f; View Current
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 reference data entities, but the regular and sorted methods would not return properly typed Lists, they would return lists of our reference data root class 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 (at the cost of clarity, IMO).
You can also bound the other way, however I have yet to come up with a usable example of this.
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.
Last Updated 08/03/2009 at 09:06:57 PM by Dave Copeland
blog comments powered by Disqus
All Content by David Copeland is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.