gpt4 book ai didi

scala - Akka mapTo 与 asInstanceOf

转载 作者:行者123 更新时间:2023-12-03 21:19:08 24 4
gpt4 key购买 nike

我正在阅读 Akka Futures Guide我看到这句话:

Also note that the Future returned by an Actor is a Future[Any] since an Actor is dynamic. That is why the asInstanceOf is used in the above sample. When using non-blocking it is better to use the mapTo method to safely try to cast a Future to an expected type



为什么 mapTo 比 asInstanceOf 更适合用于非阻塞 Future?

最佳答案

asInstanceOf 的问题这是,它会简单地转换到你想要的任何东西

scala> val f = future { 2 }
f: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@69b28a51

scala> f.asInstanceOf[Future[String]]
res9: scala.concurrent.Future[String] = scala.concurrent.impl.Promise$DefaultPromise@69b28a51

scala> f.asInstanceOf[Future[List[String]]]
res10: scala.concurrent.Future[List[String]] = scala.concurrent.impl.Promise$DefaultPromise@69b28a51

scala> res10.value
res15: Option[scala.util.Try[List[String]]] = Some(Success(2))

由于类型删除,jvm 不知道值的具体内部类型。如果您使用 mapTo相反,它将直接对值进行转换,一旦它可用并且在不匹配的类型的情况下,您将得到一个失败的 future 。
scala> f.mapTo[List[String]]
res11: scala.concurrent.Future[List[String]] = scala.concurrent.impl.Promise$DefaultPromise@2828afbb


scala> res11.value
res14: Option[scala.util.Try[List[String]]] = Some(Failure(java.lang.ClassCastException:
Cannot cast java.lang.Integer to scala.collection.immutable.List))

关于scala - Akka mapTo 与 asInstanceOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14929970/

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