Created
November 7, 2015 21:02
-
-
Save noelwelsh/20219ffd9f7e98d74770 to your computer and use it in GitHub Desktop.
WellTyped Programs Don't Go Wrong
This file contains 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
scalaVersion := "2.11.7" |
This file contains 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
sealed trait Observer[A] { | |
def observe(in :A): Unit = | |
this match { | |
case Map(f, o) => | |
// This is completely unsound. b should be of type B, which we don't | |
// have available at this point. The compiler allows us to insert | |
// anything here, causing a runtime crash. | |
val b = () | |
o.observe(b) | |
case Sink(f) => | |
f(in) | |
} | |
} | |
final case class Map[A,B](f: A => B, observer: Observer[B]) extends Observer[A] | |
final case class Sink[A](f: A => Unit) extends Observer[A] | |
object Example { | |
def go = { | |
val observer = Map[Int,Int](x => x + 1, Sink(x => println(x))) | |
observer.observe(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one. It reminds me the grievance that some often aired against Akka Actors, this was before Typed Actor was introduced.