Java/Kotlin- Akka Stream Source.reduce 在 Source 中为 null 时不起作用

标签 java scala kotlin akka akka-stream

在 Akka Streams Doku 中,给出了一个包含 null 的列表的 Scala 示例。此列表转换为源,并像示例中一样减少。不幸的是,在 Java/Kotlin 中这不会输出任何内容。

使用推文链接到 Scala 示例:https://doc.akka.io/docs/akka/current/stream/stream-quickstart.html#first-steps

这是我的 Kotlin 翻译

val system = ActorSystem.create("reactive-tweets")

val ints: Source<Int, NotUsed> = Source.from(listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, null))
ints
  .filter {
    it != null
  }
  .map {
    it * 2
  }
  .reduce { arg1, arg2 ->
    arg1 + arg2
  }
  .runWith(Sink.foreach { a -> println("sum: " + a)}, system)

我也尝试了 Source<Int?, NotUsed>并没有改变任何东西。 我很想知道后端是否发生错误或发生了什么,流没有到达打印语句。

最佳答案

Akka Streams 不允许 null元素。这记录在 https://doc.akka.io/docs/akka/current/stream/stream-flows-and-basics.html#illegal-stream-elements

您在该示例中看到的不是 null作为流元素,而是 Nil用于使用 :: 构建列表运算符(operator)。在 Scala 中,Nil是一个包含空列表的常量,::将元素添加到列表中。本例中使用这些来构造一个链表,然后将其转换为 Source。 .

关于Java/Kotlin- Akka Stream Source.reduce 在 Source 中为 null 时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62198179/

相关文章:

java - 从文件中读取N行并将其保存到新文件中

java - ListCell 不显示在 ListView 上

Java 8/9 : Can a character in a String be mapped to its indices (using streams)?

scala - 如何使用 foreachPartition 在 Spark 中为每个分区高效构建一个 ML 模型?

将函数应用于列表并通过输入获得最高结果的 Scala 方法

java - 在我的 security-config.xml 中引用特定的密码编码器

scala - 在 Scala 中,如何将 future 列表转换为返回第一个成功 future 的 future ?

android - 如何在不同模块中隐藏 Java 中 Kotlin 内部类的可见性?

android - 禁用其他子 fragment 的 View 寻呼机滑动

kotlin - 等于 Kotlin 中的重载