在Akka / Scala中使用mapTo与futures [英] Using mapTo with futures in Akka/Scala

查看:461
本文介绍了在Akka / Scala中使用mapTo与futures的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始用Akka / Scala编码,我遇到了以下问题:

I've recently started coding with Akka/Scala, and I've run into the following problem:

在范围内进行隐式转换,例如: / p>

With a implicit conversion in scope, such as:

implicit def convertTypeAtoTypeX(a: TypeA): TypeX =
    TypeX() // just some kinda conversion

这样工作:

returnsAFuture.mapTo[TypeX].map { x => ... }

但这不是:

returnsAFuture.mapTo[TypeX].onComplete { ... }

后者失败并发生类型转换异常。 (即TypeA无法转换为TypeX)

The latter fails with a type cast exception. (i.e. TypeA cannot be cast to TypeX)

很困惑。为什么?我怀疑它与Try有关,但我不知道要么猜测任何回答:(

Very confused. Why? I suspect it has something to do with Try, but I don't know enough about either to guess at any sort of answer :(

谢谢!

推荐答案

从doc:

def mapTo[S](implicit tag: ClassTag[S]): Future[S]  
    Creates a new Future[S] which is completed with this Future's result if that conforms to S's erased type or a ClassCastException otherwise.

此函数可能仅用于在具有某些继承关系的对象之间进行转换,从[T]转换到[S](它甚至不知道T!)

This function might be used only to cast between objects that are in some inheritance relationship. It doesn't expect any implicit evidence to convert from [T] to [S] (it doesn't even know about T!)

这个函数用于Akka,你要求一个actor并接收但是你知道Actor会返回String,所以你可以安全地写 actor.ask(...)。mapTo [String] 和这个因为任何都可以转换为一切,这里不使用隐式转换。

This function is used i.e. in Akka where you ask an actor and receive in response Future[Any]. But you know that an Actor will return you String so you can safely write actor.ask(...).mapTo[String] and this will work because Any can be casted to everything. No implicit conversions are used here.

现在你说你的第一个例子工作。但这行甚至不计算,因为你从来没有请求结果。为了可视化scala编译器说:你只是做一个映射(从类型X到类型Y的变化)这个未来的结果,但从来没有真正使用它,所以如果你不关心自己,为什么还要执行它?

Now you are saying your first example works. But this line is not even computed as you never request for a result. To visualize scala compiler says: well you only do a map(change from type X to type Y) a result of this future but never actually use it so why bother even executing it if you don't care yourself?

如果你在第一行添加onComplete,你会看到相同的ClassCastException。

If you added onComplete after your map in first line you would see the same ClassCastException.

这可能是你想要的这很有趣:

This is probably now what you want but this is interesting:

returnsAFuture.map { x => x.fieldOnlyInTypeX }

如果你使用x,因为它是类型TypeX一切都会工作精细。
Scala编译器将应用隐式转换为x将其转换为TypeX。这可能不是你想要的,因为x仍然是TypeA类型,并且在map中每次使用时隐式转换。

if you use "x" as if it was of type TypeX everything will work just fine. Scala compiler will apply implicit conversion to "x" to convert it to TypeX. This is probably not what you want because "x" is still of type TypeA and is converted by implicit on each use in map.

〜Krzysiek

这篇关于在Akka / Scala中使用mapTo与futures的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆