Search code examples
scalapattern-matchingcovariancealgebraic-data-typesscala-option

Scala Some redundant covariance


Scala standard library contains Option type.
The Option type itself is covariant type, this is obvious from its declaration sealed abstract class Option[+A].

The questions are:
Why its constructor Some is also covariant final case class Some[+A](x: A) extends Option[A]?
Is this somehow needed for pattern matching?
Or maybe it's done for better readability?

For me it seems redundant as I don't see any reason to use Some directly anywhere except in pattern matching but currently I can't see how it can depend on covariance.


Solution

  • First, you have to understand that, as @Dima said, Some[T] is not a constructor but a subclass for Option[T].

    Once we have established that, the questions with variance are always easier to solve with Dog and Animal:

    Is Some[Dog] a Some[Animal]? I think you'll agree that the answer is yes.

    Pragmatically, it won't change much, since you'll seldom work with Some[Dog], but rather with Option[Dog], but it may occur (say when you use an unapply of a case class whose signature returns a Some[Tuple]), so why not add the variance while we're at it?