【问题标题】:Convert Akka Iterable to java.lang.Iterable?将 Akka Iterable 转换为 java.lang.Iterable?
【发布时间】:2014-09-19 04:34:09
【问题描述】:

我想在 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 error

The docs for UntypedActorContextchildren() 方法应该返回一个'Iterable[ActorRef]',但是那个特定'Iterable'的类型定义的内联超链接导致了Scala Iterable-type 的文档而不是与Java类型相比,它们不是一回事。

这可以在实践中得到证实:从children() 调用返回的对象未通过“instanceOf Iterable”检查,并且对其调用“getClass()”返回“类akka.actor.dungeon.ChildrenContainer$ChildrenIterable”。

我似乎很清楚,这不是 Java Iterable 并且错误是适当的。但是我如何将它强制或编组为 Java Iterable? This link in the Scala docs 建议有 Scala->Java 的转换函数,但我无法确定要导入的内容或如何从 Java 调用它们;我见过的唯一例子是 Scala。

附:我意识到我可以使用 while 循环和 children().iterator() 返回的 Scala-Iterator 在这里构造等效于 for-each 循环。我真正想要的是了解如何使用 Scala 提供的类型转换例程。

【问题讨论】:

    标签: java scala akka


    【解决方案1】:

    如果您使用 Java,您将使用 UntypedActor 及其 UntypedActorContext,它提供了一个getChildren()-方法: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 immutable
    

    【讨论】:

      【解决方案2】:

      我没用过 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
      }
      

      【讨论】:

      • 这清除了它,谢谢!我会投票,但我还没有足够的业力来投票。
      • @SAyotte 如果您是问题的提问者,那么您接受答案,而不是投票。
      猜你喜欢
      • 2010-11-07
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      相关资源
      最近更新 更多