Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Language IDEs » Java Development Tools (JDT) » NonNull and java.lang.Optional orElse()
NonNull and java.lang.Optional orElse() [message #1749868] Tue, 13 December 2016 11:36 Go to next message
Frank Benoit is currently offline Frank BenoitFriend
Messages: 179
Registered: July 2009
Senior Member
Hi

To just accept a null in case a Option is empty, you can use

Optional<String> opt = ....;
@NonNull str1 = "str1";
@Nullable str2 = read();

@Nullable String res0 = opt.orElse(null);
@NonNull String res1 = opt.orElse(str1);
@Nullable String res2 = opt.orElse(str2);


Is there a way to make this work?
Or would it be needed to ask for a new method in Optional, e.g. orElseNullable(), orNull() ?

Frank
Re: NonNull and java.lang.Optional orElse() [message #1749877 is a reply to message #1749868] Tue, 13 December 2016 13:42 Go to previous messageGo to next message
Stephan Herrmann is currently offline Stephan HerrmannFriend
Messages: 1853
Registered: July 2009
Senior Member
In class Checks we provide a solution for the first variant:
public static <T> @Nullable T asNullable(@NonNull Optional<T> optional)


Providing a nullable fallback is not supported. Is that really a useful pattern? What's the use of the fallback when it cannot be relied upon itself?

Stephan
Re: NonNull and java.lang.Optional orElse() [message #1750180 is a reply to message #1749877] Fri, 16 December 2016 19:53 Go to previous messageGo to next message
Frank Benoit is currently offline Frank BenoitFriend
Messages: 179
Registered: July 2009
Senior Member
Hi Stephan,

If there would be a way to say "the return nullability is the same as the one of the first parameter", this would solve it perfectly.

But as i understand, with Check.asNullable, I can annotation
@NonNull T Optional.orElse( @NonNull T t )
and replace those places where I used orElse(null) with the Check.asNullable.

thanks
Frank
Re: NonNull and java.lang.Optional orElse() [message #1750219 is a reply to message #1750180] Sun, 18 December 2016 22:12 Go to previous message
Stephan Herrmann is currently offline Stephan HerrmannFriend
Messages: 1853
Registered: July 2009
Senior Member
do you envision s.t. like
<T> T fromOptionalOrElse(@NonNull Optional<@NonNull T> optional, T fallback)


Here <T> could be either a nullable or a nonnull type - to be inferred from fallback and the target type, whereas the optional would use the nonnull variant of this type.

Still I don't understand whether/why you want a nullable fallback.
Previous Topic:Null annotation with generated code
Next Topic:Setting breakpoints in foreign sources
Goto Forum:
  


Current Time: Fri Apr 26 03:26:27 GMT 2024

Powered by FUDForum. Page generated in 0.03498 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top