如何编写“asInstanceOfOption"在斯卡拉 [英] How to write "asInstanceOfOption" in Scala

查看:47
本文介绍了如何编写“asInstanceOfOption"在斯卡拉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以编写一个asInstanceOfOption"方法来执行以下(虚假)代码的意图?

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 

推荐答案

EDIT 以下是我的原始答案,但您现在可以使用

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


您可以使用清单来绕过类型 T 在编译时被擦除的事实:

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]

然后可以使用:

scala> asInstanceOfOption[Int]("Hello")
res1: Option[Int] = None

scala> asInstanceOfOption[String]("World")
res2: Option[String] = Some(World)

您甚至可以使用隐式转换使其成为Any上可用的方法.我想我更喜欢方法名称 matchInstance:

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    

更新了 2.9.x 的代码,其中不能使用 Any 而只能使用 AnyRef:

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
  }   
}

这篇关于如何编写“asInstanceOfOption"在斯卡拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆