Skip to content

Instantly share code, notes, and snippets.

@machisuji
Created February 2, 2012 15:39
Show Gist options
  • Select an option

  • Save machisuji/1724042 to your computer and use it in GitHub Desktop.

Select an option

Save machisuji/1724042 to your computer and use it in GitHub Desktop.
case and call-by-name?
receive("hallo") {
case "hallo" => "selber" // selber should not be evaluated at this point
} // result Some(selber)
def receive[T](data: String)(fun: PartialFunction[String, Function0[T]]): Option[T] = {
val action = fun orElse new PartialFunction[String, Function0[T]] {
def isDefinedAt(str: String) = true
def apply(str: String) = () => {
println("no match :(")
null.asInstanceOf[T]
}
} apply data
Some(action()).filter(null ne)
}
receive("hallo") {
case "hallo" => () => { "selber" }
} // result: Some(selber)
receive("test") {
case "hallo" => () => { "selber" }
} // result: None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment