Created
May 31, 2012 01:01
-
-
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
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
/** | |
* 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