How to write “asInstanceOfOption” in Scala

前端 未结 3 1563
佛祖请我去吃肉
佛祖请我去吃肉 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:33

    Here's an elaboration on oxbow_lake's updated answer, further updated to require Scala 2.10:

    // Implicit value class
    implicit class Castable(val obj: AnyRef) extends AnyVal {
      def asInstanceOfOpt[T <: AnyRef : ClassTag] = {
        obj match {
          case t: T => Some(t)
          case _ => None
        }
      }
    }
    

    This can be used by doing:

    "Hello".asInstanceOfOpt[String] == Some("Hello") // true
    "foo".asInstanceOfOpt[List[_]] == None // true
    

    However as mentioned in other answers this doesn't work for primitives because of boxing issues, nor does it handle generics because of erasure. To disallow primitives, I restricted obj and T to extend AnyRef. For a solution that handles primitives, refer to the answer for Matt R's followup question:

    How to write asInstanceOfOpt[T] where T <: Any

    Or use shapeless's Typeable, which handles primitives as well as many erasure cases:

    Type casting using type parameter

提交回复
热议问题