Last active
July 22, 2016 07:50
-
-
Save larsrh/3e2d3789abc0a35b7dce7275b50ba816 to your computer and use it in GitHub Desktop.
safe head/tail on lists using covariance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Initial idea courtesy of @dwijnand | |
// Improved by @fthomas | |
sealed trait List[+T] { | |
def head: Option[T] | |
} | |
final case class Cons[T](h: T, t: List[T]) extends List[T] { | |
val head: Some[T] = Some(h) | |
} | |
final case object Nil extends List[Nothing] { | |
val head = None | |
} | |
// scala> Cons(1, Nil).head.x | |
// res0: Int = 1 | |
// scala> Nil.head | |
// res1: None.type = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This can be made even simpler: