What are the alternatives to subtype polymorphism in scala?
Asked Answered
P

1

15

I'm interested to know the complete set of alternatives to subtype polymorphism in scala.

Polyphone answered 29/8, 2010 at 19:52 Comment(0)
M
23

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.

Muff answered 29/8, 2010 at 20:20 Comment(5)
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.Corry
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: people.cs.kuleuven.be/~adriaan.moors/files/higher.pdfGlebe
Excellent comments. Editing.Muff
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 relatedInbound
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).Muff

© 2022 - 2024 — McMap. All rights reserved.