2013-02-18 227 views
14

我在看Akka Futures Guide,我看到这样一句话:阿卡mapTo与asInstanceOf

还要注意的是男演员返回的未来是一个未来的[任何]因为一个演员是动态的。这就是为什么asInstanceOf用于上面的示例。当使用非阻塞时,最好使用mapTo方法来安全地尝试将Future转换为预期类型

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

回答

21

asInstanceOf这里的问题是,它会简单地强制转换为任何你想要

scala> val f = future { 2 } 
f: scala.concurrent.Future[Int] = [email protected] 

scala> f.asInstanceOf[Future[String]] 
res9: scala.concurrent.Future[String] = [email protected] 

scala> f.asInstanceOf[Future[List[String]]] 
res10: scala.concurrent.Future[List[String]] = [email protected] 

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

因为类型擦除的JVM不知道具体的内部类型的值的。如果您使用mapTo来替代,则它会直接在该值上进行强制转换,一旦该值可用,并且在不匹配类型的情况下,您将获得失败的未来。

scala> f.mapTo[List[String]] 
res11: scala.concurrent.Future[List[String]] = [email protected] 


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

它与其说mapTo是在这种情况下更好,因为这asInstanceOf是不可用的:他们与asInstanceOf例如用它来结果转换从AnyString,但有无阻塞的未来,你没有结果呢,甚至作为一个Any。相反,您有一个Future[Any],并且您需要使用其mapTo方法将其包装为Future[String]