How to write “asInstanceOfOption” in Scala

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

    EDIT Below is my original answer but you can accomplish this now with

    def asInstanceOfOption[T: ClassTag](o: Any): Option[T] = 
      Some(o) collect { case m: T => m}
    

    You could use manifests to get around the fact that the type T is erased at compile time:

    scala> import scala.reflect._
    import scala.reflect._
    
    scala> def asInstanceOfOption[B](x : Any)(implicit m: Manifest[B]) : Option[B] = {
       | if (Manifest.singleType(x) <:< m)
       |   Some(x.asInstanceOf[B])
       | else
       |   None
       | }
    asInstanceOfOption: [B](x: Any)(implicit m: scala.reflect.Manifest[B])Option[B]
    

    Then this could be used:

    scala> asInstanceOfOption[Int]("Hello")
    res1: Option[Int] = None
    
    scala> asInstanceOfOption[String]("World")
    res2: Option[String] = Some(World)
    

    You could even use implicit conversions to get this to be a method available on Any. I think I prefer the method name matchInstance:

    implicit def any2optionable(x : Any) = new { //structural type
      def matchInstance[B](implicit m: Manifest[B]) : Option[B] = {
        if (Manifest.singleType(x) <:< m)
          Some(x.asInstanceOf[B])
        else
          None
      }   
    }
    

    Now you can write code like:

    "Hello".matchInstance[String] == Some("Hello") //true
    "World".matchInstance[Int] == None             //true    
    

    EDIT: updated code for 2.9.x, where one can't use Any but only AnyRef:

    implicit def any2optionable(x : AnyRef) = new { //structural type
      def matchInstance[B](implicit m: Manifest[B]) : Option[B] = {
        if (Manifest.singleType(x) <:< m)
          Some(x.asInstanceOf[B])
        else
          None
      }   
    }
    

提交回复
热议问题