Skip to content

Instantly share code, notes, and snippets.

Null pointer exceptions can be prevented at compile time using a simple data type borrowed from Haskell.

data Maybe a = Nothing | Just a

The Maybe type

The type class encoding in my previous post on the subject is a bit rubbish:

  • type class instances are classes, which have a non-zero creation cost;
  • they do not have self-type parameters, so are not necessarily distinguishable at the type level; and
  • they do not provide for derived operations.

The Maybe type I described could do with some type class instances, so let’s try out a new encoding.

@jedahu
jedahu / Maybe.scala
Last active August 25, 2016 06:56
Get Typed (Scala)
package gettyped
sealed abstract class Maybe[A] {
def fold[B](nothing: => B, just: A => B): B = this match {
case Nothing() => nothing
case Just(a) => just(a)
}
}
private final case class Nothing[A]() extends Maybe[A] {}

Keybase proof

I hereby claim:

  • I am jedahu on github.
  • I am jedahu (https://keybase.io/jedahu) on keybase.
  • I have a public key ASAEDZtMXX9XenWwUEArDrIcIWeR7Zpc2RIfw-UPq5ILjgo

To claim this, I am signing this object: