Skip to content

Instantly share code, notes, and snippets.

@propensive
Created January 27, 2016 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save propensive/14d9b814f643902e7aff to your computer and use it in GitHub Desktop.
Save propensive/14d9b814f643902e7aff to your computer and use it in GitHub Desktop.
Type Matching in Scala
scala> :paste
// Entering paste mode (ctrl-D to finish)
val fn = tmatch(
when[Int] { i => i + 1 }
when[String] { s => s.toInt }
when[Symbol] { s => 3.1415926 }
when[Double] { d => "You entered a double" }
)
// Exiting paste mode, now interpreting.
fn: typematch.tmatch[Double,Symbol,String,Int,Nothing,Nothing,Nothing,String,Double,Int,Int,Nothing,Nothing,Nothing,Nothing] = tmatch(Cons(<function1>,Cons(<function1>,Cons(<function1>,Cons(<function1>,null)))))
scala> fn(1)
res0: Int = 2
scala> fn("3")
res1: Int = 3
scala> fn('pi)
res2: Double = 3.1415926
scala> fn(4.0)
res3: String = You entered a double
scala> fn(true)
<console>:15: error: could not find implicit value for parameter m: fn.Stack[Boolean]
fn(true)
^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment