Nicolas Neudeck
Nicolas Neudeck

Reputation: 33

Java/Kotlin- Akka Stream Source.reduce does not work if null in Source

In the Akka Streams Doku, a Scala example with a list containing a null is given. This list transformed into a Source, and reduced like in the example. Unfortinutly, in Java/Kotlin this does not output anything.

Link to Scala example with tweets: https://doc.akka.io/docs/akka/current/stream/stream-quickstart.html#first-steps

Here my translation into 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)

I also tried the Source<Int?, NotUsed> and didn't change anything. I would love to know if in the backend an error occurs or what happens, that the stream does not reach the print statement.

Upvotes: 3

Views: 295

Answers (1)

Tim Moore
Tim Moore

Reputation: 9482

Akka Streams does not allow null elements. This is documented at https://doc.akka.io/docs/akka/current/stream/stream-flows-and-basics.html#illegal-stream-elements

What you see in that example isn't null as a stream element, but rather Nil being used to construct a list using the :: operator. In Scala, Nil is a constant containing an empty list, and :: prepends an element to a list. These are used in this example to construct a linked list that is then converted to a Source.

Upvotes: 2

Related Questions