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[
At the time of the writing of oxbow_lakes's answer (late '09), I believe scala.util.Try
was not available, however, now (i.e. as of 2.10) I think scala.util.Try
is the preferred (or well at least nicer-looking) way of doing this:
scala> Try((3).asInstanceOf[String]).toOption
res0: Option[String] = None
scala> Try("hello".asInstanceOf[String]).toOption
res1: Option[String] = Some(hello)
This relies on exceptions, so probably not the preferred style for performance critical blocks of code.