What do I use for a variant in a UML class diagram

algebraic-data-typefunctional programminguml

Does standard UML specify how a variant (aka tagged union, discriminated union, sum type, etc) should be depicted in a class diagram?

Best Answer

The Unified Modeling Language is not so much unifying programming paradigms. It is dramatically focused towards object-oriented programming (hence, f.ex. its most popular diagram being the class diagram). In contrast, sum types are typically a feature of functional languages (like F#, Haskell, etc.).

I'm afraid to inform you that UML is probably not a good choice to model programs that will be developed with a functional language. A huge bag of their features do not have direct correspondences in UML unfortunately. Features that form the bread-and-butter of FP, like first-class functions, type constructors, etc., are troublesome to represent in UML, or flat out impossible.

If you must represent sum types, then you could model a representation that is close to their implementation in Scala, where you actually define a base class/trait/interface and derive the individual sum types. Something like this (simplified):

sealed trait Option[+A]
case object None extends Option[Nothing]
case class Some(value : T) extends Option[T]

Of course, you will fall short of modelling this in several aspects (trait? case class? covariance? sealed?), but that is my general experience when you try to model non-OOP features in UML.

Related Topic