加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Scala中写“asInstanceOfOption”

发布时间:2020-12-16 09:44:37 所属栏目:安全 来源:网络整理
导读:是否可以编写一个“asInstanceOfOption”方法来执行以下(伪造)代码的意图? def asInstanceOfOption[T](o: Any): Option[T] = if (o.isInstanceOf[T]) Some(o.asInstanceOf[T]) else None 解决方法 编辑以下是我原来的答案,但是现在可以完成这个 def asInst
是否可以编写一个“asInstanceOfOption”方法来执行以下(伪造)代码的意图?

def asInstanceOfOption[T](o: Any): Option[T] =
   if (o.isInstanceOf[T]) Some(o.asInstanceOf[T]) else None

解决方法

编辑以下是我原来的答案,但是现在可以完成这个

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:

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

现在你可以编写如下代码:

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

编辑:2.9.x的更新代码,其中不能使用Any但只有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
  }   
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读