gpt4 book ai didi

scala - 如何在 Scala 中编写 "asInstanceOfOption"

转载 作者:行者123 更新时间:2023-12-03 10:26:51 24 4
gpt4 key购买 nike

是否可以编写一个“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}

您可以使用 list 来绕过类型 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
}
}

关于scala - 如何在 Scala 中编写 "asInstanceOfOption",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1803036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com