How to write “asInstanceOfOption” in Scala

前端 未结 3 1565
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 22:36

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[         


        
3条回答
  •  别那么骄傲
    2021-01-30 23:12

    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.

提交回复
热议问题