Is it possible to return the first non-empty value for different types of Java using options?

String myFunction(Optional<ClassWithIdAsString> instanceWithIdAsString, Optional<ClassWithIdAsLong> instanceWithIdAsLong) {

String resultId = instanceWithIdAsString.map(ClassWithIdAsString::getId)
                .map(id -> String.valueOf(id))
                .orElseGet(t -> instanceWithIdAsLong
                .map(ClassWithIdAsLong::getId));
return resultId;
}

The above code does not compile ... I get:

Invalid return type in method reference: cannot convert java.lang.String to U

At compile time:

incompatible types: incompatible parameter types in lambda expression

By the long names above, I mean the Long wrapper class. I did a lot of research and did not find anything like it, but I hope for some workaround. Creating above id of the same type is not an option for me.

+4
source share
3 answers
 String id = instanceWithIdAsString.map(ClassWithIdAsString::getId)
            .map(id -> String.valueOf(id))
            .orElseGet(() -> instanceWithIdAsLong
            .map(ClassWithIdAsLong::getId).orElse(""));

Doesn't ClassWithIdAsString :: getId return String as ID and ClassWithIdAsLong :: getId long as ID?

If so, it should be the other way around:

String id = instanceWithIdAsString.map(ClassWithIdAsLong::getId)
            .map(id -> String.valueOf(id))
            .orElseGet(() -> instanceWithIdAsLong
            .map(ClassWithIdAsString::getId).orElse(""));

, null, "".

, .

, .

+2

:

  • id map, ​​ .
  • orElseGet Supplier, t -> ..., Supplier.
  • map orElseGet Optional<Long>, String.
  • map(ClassWithIdAsString::getId) Optional<String>, String.valueOf .map(id -> String.valueOf(id)) ( ) - valueOf(Object obj).

:

String id = instanceWithIdAsString
                .map(ClassWithIdAsString::getId)                 
                .orElseGet(() -> String.valueOf(instanceWithIdAsLong
                                       .map(ClassWithIdAsLong::getId)
                                       .orElse(-1)));
+2

The problem is the last call to map () on the optional inside of the orElse clause. Since it is optional from a string, orElse should return a string, but inside it you return optional.

0
source

Source: https://habr.com/ru/post/1692391/


All Articles