I'm interested to know the complete set of alternatives to subtype polymorphism in scala.
+17
A:
The basic tools for of achieving statically-checkable polymorphism in Scala are
- Subtyping (bog-standard OO polymorphism)
- Type parameterization (allows polymorphic variance and constraints)
- Self-typing (allows restriction and specialization of OO polymorphism)
- Implicit conversion (allows post-facto polymorphic construction)
- Structural typing (allows polymorphism based on features, rather than type)
- General type bounds (allowing extremely precise constraints on allowed polymorphism)
- Pattern matching (allows polymorphism based on data structure, similar to abstract data types)
- Higher-kinded types (allowing polymorphism over polymorphic constructions)
Calling all of these 'alternatives' is probably the wrong word, since they are so well integrated. It's not uncommon for some polymorphic algorithms to be expressed by using of several of these tools in conjunction.
It's also worth noting the place of for-comprehensions in Scala polymorphism. For comprehensions don't seem particularly polymorphic. Below the surface, for-comprehensions are just syntactic sugar for calls to filter/map/flatMap, and implementations of those methods tend to be highly polymorphic. Thus, what look to be comparatively simple for-loops can result in some really impressive polymorphic effects.
Dave Griffith
2010-08-29 20:20:46
It's probably more accurate to describe structural typing as "based on features of the value" than on "behavior [of the value]," since behavior is an opaque property from the perspective of the type system.
Randall Schulz
2010-08-29 21:17:41
I miss "support for higher kinded types" in your list, which is one of the most powerful features of Scala. I think the best reference is still Adrian Moors' paper: http://people.cs.kuleuven.be/~adriaan.moors/files/higher.pdf
Landei
2010-08-29 21:39:33
Excellent comments. Editing.
Dave Griffith
2010-08-29 22:49:06
Thanks guys, very useful.
Channing Walton
2010-08-31 06:29:03
You forgot type classes. In fact, I think the only polymorphism alternatives to subtyping are structural types and type classes. The rest are either enhancements on subtyping (generics, constraints) or not related
IttayD
2010-09-04 18:07:26
Type classes in scala implemented mostly via implicit conversion, which is why I didn't break it out explicitly. That certainly fits in with my description of implicit conversion as allowing post-facto polymorphism.I'm not sure how you consider generics to be enhancements to subtyping. One could easily imagine languages that had generics but no subtyping (IIRC, early versions of Ada followed that pattern).
Dave Griffith
2010-09-04 20:33:46