11

In Scala i can write a short method like this:

def xy(
  maybeX: Option[String],
  maybeY: Option[String]): Option[String] = {

  for {
    x <- maybeX
    y <- maybeY
  } yield {
    s"X: $x Y: $y"
  }
}

Does Java have something similar, when it comes to two or more Optional<> variables?

senjin.hajrulahovic
  • 2,961
  • 2
  • 17
  • 32
Lasse Frandsen
  • 141
  • 1
  • 7
  • Sure you can do something like this, it would be more syntax though as Java doesn't have first class functional programming support. – Thomas Mar 08 '19 at 09:13
  • 3
    To increase the chance of getting more helpful answers, you can explain what the scala code does, so that people who don't know scala can see what you are trying to do. – Sweeper Mar 08 '19 at 09:27
  • 1
    @Sweeper It is perfectly reasonable to ask how to convert from one language to another without having to explain how those languages work. If you don't understand one of the languages then don't answer the question. – Tim Mar 08 '19 at 11:09
  • @Tim I never said it is unreasonable to ask a question like this. I said “to get more helpful answers”. – Sweeper Mar 08 '19 at 11:11
  • @Sweeper You won't get a more helpful answer from someone who doesn't understand Scala. – Tim Mar 08 '19 at 12:11

1 Answers1

12

This would be the appropriate alternative:

Optional<String> maybeXY = maybeX.flatMap(x -> maybeY.map(y -> x + y));

The scala for comprehension is just syntactic sugar for map, flatMap and filter calls.

Here's a good example: How to convert map/flatMap to for comprehension

senjin.hajrulahovic
  • 2,961
  • 2
  • 17
  • 32
  • 4
    I'd probably write it like that in Scala, too :-) – Thilo Mar 08 '19 at 13:01
  • 6
    You don't seem to realize the significance of Scala's for-comprehension or Haskell's do notation. The point is that Scala's for-comprehension provides a neat syntax for long chains of `flatMap` and `map` calls. In Java you'd end up with a right-skewed chain of method calls with tons of parentheses making the code untidy and hard to follow. – Random dude Feb 29 '20 at 01:20