我想在for-each循环中迭代给定Actor的子级,如下所示:
for(ActorRef child: this.getContext().children()){
// do things
}但是,这会产生一个错误:
HelloWorld.java:78: error: for-each not applicable to expression type
for(ActorRef child: this.getContext().children())
^
required: array or java.lang.Iterable
found: Iterable<ActorRef>
1 errorUntypedActorContext的文档说,children()方法应该返回一个'Iterable[ActorRef]',但是针对特定'Iterable‘的类型定义的内联超链接会导致Scala Iterable类型的docs,而不是Iterable[ActorRef]类型,这不是一回事。
这一点可以在实践中得到证实:从children()调用返回的对象失败了"instanceOf Iterable“检查,对其调用"getClass()”返回“类akka.actor.dungeon.ChildrenContainer$ChildrenIterable”。
在我看来,这显然是,而不是Java的Java,而且错误是适当的。但是,我如何将它强制或马歇尔到Java中呢?Scala文档中的这个链接建议Scala->Java有转换函数,但我不能直接说明从Java导入什么或如何调用它们;我看到的唯一例子是Scala。
我意识到我可能可以使用children().iterator()返回的时间循环和Scala来构造相当于for-each循环的循环。我真正想要了解的是如何使用Scala提供的类型转换例程。
发布于 2014-07-28 03:58:54
我还没用过Scala,但是医生说
java.lang.Iterable<ActorRef> jChildren = JavaConversions.asJavaIterable (this.getContext().children());
for (ActorRef child: jChildren) {
// do stuff
}注意:如果在同一个类中使用了两种类型的Iterable,则需要在声明中展开java.lang.Iterable,以确保它使用正确的类。
或者,您可以在一行中这样做:
for (ActorRef child: JavaConversions.asJavaIterable(this.getContext().children())) {
// do stuff
}发布于 2014-07-28 13:57:31
如果您使用的是Java,您将使用UntypedActor及其UntypedActorContext,它提供了一个getChildren()-method:http://doc.akka.io/japi/akka/2.3.4/akka/actor/UntypedActorContext.html
医生:
java.lang.Iterable<ActorRef> getChildren()
Returns an unmodifiable Java Collection containing the linked actors, please note that the backing map is thread-safe but not immutablehttps://stackoverflow.com/questions/24987616
复制相似问题