2

I'm stuck with a simple problem: I have a java.util.Optional and want to use the orElseThrow method to throw an exception if value is not present. However I cannot figure the right syntax to do this in Xtend. In Java, I would do:

Optional<String> host = ... // get from some method
host.orElseThrow(() -> new IllegalArgumentException("Host is not provided"));

But this does not compile in Xtend. The error message in Eclipse is like this (where MyClass is the name of my custom class):

Multiple markers at this line
- Type mismatch: cannot convert from Pair<MyClass, IllegalArgumentException> to Supplier<? extends Throwable>
- no viable alternative at input ')'

Please help!

Software Craftsman
  • 2,999
  • 2
  • 31
  • 47

1 Answers1

4

Try something like:

val Optional<String> host = ... // get from some method
host.orElseThrow[new IllegalArgumentException("Host is not provided")]

See the documentation about lambda expressions.

(-> is an operator in Xtend but it is not related to lambda expressions. See the documentation about operators and search for the Pair Operator.)

snorbi
  • 2,590
  • 26
  • 36
  • Thanks! This syntax works! Also, with the help of the link, another notation can also be used: host.orElseThrow( | new IllegalArgumentException("Host is not provided")) – Software Craftsman Oct 14 '16 at 08:16