scala - Akka mapTo 与 asInstanceOf

标签 scala akka future

我正在阅读 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/

相关文章:

DART lang,FUTURE 函数,then 链

Scala 最佳实践 : mapping 2D data

bash - 如何使用Spark添加HDFS数据

scala - 使用 Apache Spark 从 HDFS 序列文件生成键值对

java - Playframework 从 2.4 迁移到 2.5 : java. lang.IllegalStateException:尝试调用 Materialize()

java - Akka-Java 路由问题

json - Scala Play Json 中 JsPath 到数组

java - 如何随时取消异步计算?

通过套接字发送字符串时 Java 流损坏

Scala Future 用于理解 : sequential vs parallel