javascalascala-java-interop

How to convert Scala `for..yield` (for comprehension) to Java?


How to convert the following scala to java code?

for {
  x <- List(1, 2)
  y <- List(3, 4)
} yield (x, y)

Is it possible? what is yield?

I guess it's possible to convert any scala code to java...


Solution

  • @Tim already explained what is for..yield.

    The Java code to do the same would be:

    // Java doesn't have tuples, create your own type
    record Pair(int x, int y) {}
    
    List<Pair> result = 
      List.of(1, 2)
          .stream()
          .flatMap(x -> List.of(3, 4)
                            .stream()
                            .map(y -> new Pair(x, y))
          )
          .toList();
    

    IMHO this is a great example of the conciceness and exprenessiveness of Scala, especially when working with collections.