Skip to content

Instantly share code, notes, and snippets.

@noelwelsh
Created November 7, 2015 21:02
Show Gist options
  • Select an option

  • Save noelwelsh/20219ffd9f7e98d74770 to your computer and use it in GitHub Desktop.

Select an option

Save noelwelsh/20219ffd9f7e98d74770 to your computer and use it in GitHub Desktop.
WellTyped Programs Don't Go Wrong
scalaVersion := "2.11.7"
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)
}
}
@channingwalton

Copy link
Copy Markdown

Does the compiler infer the type of Mat(f,o) in the pattern match as Map[Any,Any]?

@isaka

isaka commented Nov 7, 2015

Copy link
Copy Markdown

Nice one. It reminds me the grievance that some often aired against Akka Actors, this was before Typed Actor was introduced.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment