Covariance in Scala

August 14, 2014

Starting with the Option implementation from the option monad exercise:

sealed trait Option[A] { ... }
case class Some[A](a: A) extends Option[A]
case class None[A]() extends Option[A]

Make Option covariant in its type A so that only a single None instance is needed:

case object None extends Option[???]
def quotient(divisor: Int)(dividend: Int): Int =
  dividend / divisor

def remainder(divisor: Int)(dividend: Int): Option[Int] =
  (dividend % divisor) match {
    case 0 => None
    case r => Some(r)
  }

val x3 =
  for {
    x <- Some(42)
    q  = quotient(2)(x)
    r <- remainder(4)(x)
  } yield (x,q,r)

println(x3) // Some((42,21,2))

Solution

Here is one possible solution.
sealed trait Option[+A] {

  def map[B](f: A => B): Option[B] =
    this match {
      case Some(a) => Some(f(a))
      case None  => None
    }

  def flatMap[B](f: A => Option[B]): Option[B] =
    this match {
      case Some(a) => f(a)
      case None  => None
    }

  override def toString(): String =
    this match {
      case Some(a) => "Some(" + a + ")"
      case None  => "None"
    }
}

case class Some[A](a: A) extends Option[A]
case object None extends Option[Nothing]

Demo

This file is literate Scala, and can be run using Codedown:

$ curl https://earldouglas.com/exercises/scala-covariance.md |
  codedown scala |
  xargs -0 scala -nc -e
Some((42,21,2))