Is it possible to write an “asInstanceOfOption” method that would do what is intended by the following (bogus) code?
def asInstanceOfOption[T](o: Any): Option[T] =
if (o.isInstanceOf[T]) Some(o.asInstanceOf[T]) else None
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
EDIT Below is my original answer but you can accomplish this now with
You could use manifests to get around the fact that the type
Tis erased at compile time:Then this could be used:
You could even use implicit conversions to get this to be a method available on
Any. I think I prefer the method namematchInstance:Now you can write code like:
EDIT: updated code for 2.9.x, where one can’t use
Anybut onlyAnyRef: