Search code examples
exceptionoption-typextend

What is the right syntax for Optional.orElseThrow in Xtend?


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!


Solution

  • 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.)