Skip to content

Instantly share code, notes, and snippets.

@etorreborre
Created May 31, 2012 01:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etorreborre/2839993 to your computer and use it in GitHub Desktop.
Save etorreborre/2839993 to your computer and use it in GitHub Desktop.
Type inference trick to avoid unchecked - DOESN'T WORK... warnings in pattern matching
/**
* UPDATE: this trick doesn't work here because when using 'asInstanceOf', Nothing is inferred as being the expected type, thus the conversion fails at run-time.
*/
/**
* Let's say you have some ugly casting to do
*/
// this doesn't compile with something like: "expected _, got Any"
function match {
case f: Function1[_,_] => f(a)
case f: Function2[_,_,_] => f(a, b)
}
// this raises warnings about type erasure in patterns
function match {
case f: Function1[A,B] => f(a)
case f: Function2[A,B,C] => f(a, b)
}
// this works ok!
// courtesy of the ScalaTest mailing-list: http://bit.ly/KXOHgz
function match {
case f: Function1[_,_] => f(a.asInstanceOf)
case f: Function2[_,_,_] => f(a.asInstanceOf, b.asInstanceOf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment