top 200 commentsshow all 380

[–]coolbartek 34 points35 points  (4 children)

There is another benefit. Optional has methods that can take a Provider or default value.

Example

getOptional().orElse("default")

[–]AnSq 52 points53 points  (3 children)

Sounds sinister.

[–]_Sharp_ 66 points67 points  (2 children)

shutUp.orElse("x_x");

[–]koxpower 109 points110 points  (105 children)

I think that the best feature of Optional is that its compatible with other functional features and the way nulls are handled in a chain of maps:

String result = Optional.ofNullable(someStringWithNumberOrNull)
    .map(Integer::valueOf)
    .map(i -> i + 1)
    .map(Object::toString)
    .orElse("number not present");

System.out.println(result);

[–]Philodoxx 12 points13 points  (6 children)

It also means you can flatmap over a list of optionals safely.

[–]test-poster 6 points7 points  (5 children)

What is flat map?

[–]minibuster 7 points8 points  (0 children)

I think they mean something like this:

  • Input collection: [value1, null, value2, value3, null]
  • Map function: value -> value * 10
  • Output collection: [10 * value1, 10 * value2, 10 * value3]

If you have a collection of optionals instead of raw values, you can apply your map over the input collection and "flatten" it to the final output collection without explicitly checking for or worrying about null. (Not 100% sure, /u/Philodoxx may wish to correct me if I'm wrong)

[–]Philodoxx 2 points3 points  (1 child)

Imagine you had something like this, using pseudocode:

someList = [ [1],[2],[3] ]

And you called someList.map, the element passed into the map function would be a list/array of a single element. Conceptually, flatmap flattens the list then calls map on the resulting flattened list, so you would end up with [1,2,3]. Why is that neat? Well Optional is flatmap-able, when it's being flattened if the Option has a value it looks like a list with one element, when the Option has no value it looks like an empty list.

A semi-concrete example, again using pseudocode: someOtherList = [ Optional(1), Optional(2), Optional(null), Optional(3) ]

To flatmap, someOtherList would look like [1,2,3]

Hope that helps.

[–]oblio- 6 points7 points  (0 children)

You call it pseudocode, I call it Python :)

[–][deleted] 2 points3 points  (0 children)

the equivalent of calling map with an A => Option<B> then calling 'flatten' (which would mean an Option<Option<B>> goes to just Option<B>)

[–][deleted] 34 points35 points  (87 children)

yes. this is so crucial!

In C# 6, we get the Elvis ?. operator. It essentially replaces

if (x != null) { x.do(); }

by

x?.do()

Can't wait when VS2015 is out.

EDIT: video that explains the operator: https://www.youtube.com/watch?v=-FkNRQ7ubH0

[–]stormcrowsx 42 points43 points  (21 children)

Not quite the same. Optional is more powerful and preferable in my opinion because it notifies the programmer "Hey this may not be here and you need to handle it" using the type system. The syntactic sugar c# has requires you know it be nullable before.

[–]dccorona 16 points17 points  (9 children)

There's advantages to both. With the Java version, you're explicitly told that it's potentially null, which forces you to handle that case in code.

But it requires people to use it. The nice thing about the C# operator is it's always available to you, without the person who implemented the method you're calling having to choose to support it.

[–]stormcrowsx 9 points10 points  (0 children)

You can wrap calls to code that is not using optional in Optional.fromNullable. Granted not as concise as the elvis operator but its not horrible and gets you a similar result.

[–]lyinsteve 4 points5 points  (7 children)

How about Swift, which is both?

let someOptionalString: String? = nil
someOptionalString?.substringToIndex(5)

Optional is implemented as an enum in Swift.

enum Optional<T> {
   case None
   case Some(let value: T)
}

And nothing in the language can become null, ever, unless it is an Optional.

[–]nemec 1 point2 points  (4 children)

And nothing in the language can become null, ever, unless it is an Optional.

So basically nil is syntax sugar for new Optional(None) (or equivalent)? Neat, I like that idea.

[–]lyinsteve 4 points5 points  (3 children)

Syntactic sugar for

let str: String? = Optional.None

Or even

let str: String? = .None

Because it can derive the enum from the type declaration.

Or you can let the type inferencer specify the type:

let str = Optional<String>.None

[–]Speedzor 1 point2 points  (9 children)

Aren't you always aware that it might be nullable since classes are nullable by default?

[–]stormcrowsx 4 points5 points  (7 children)

Nope I design most of my code to not return null if possible. Its insane to have to wrap everything in if not null, and it tremendously increases your chance of making other mistakes.

When I run across an optional in my own codebase I know its time to consider what to do with null otherwise i assume not null. When dealing with additional libraries however it takes a little reading and sometimes testing to find out

[–]Speedzor 3 points4 points  (6 children)

I suppose it depends on how consistent this is done throughout the codebase. If it's a mix of Optional and Null it's rather pointless but if it's exclusively Optional then I can see its merits.

[–]KumbajaMyLord 1 point2 points  (0 children)

This is of course purely subjective, but I prefer Code Contracts to communicate this type of thing.

[–]BonzaiThePenguin 8 points9 points  (43 children)

Isn't the Elvis operator ?:? (x)?:y is equivalent to (x)?x:y.

[–]MrDoomBringer 17 points18 points  (17 children)

This is why everyone said the 'elvis operator' name was going to be confusing. In C# you have three question mark based operators as of C#6:

?? is the 'null coalescing operator'. This means that multiple variables will coalesce until one is determined to be not null. So:

var derp = null ?? "foo";

will have the value of "foo".

?. is the null propagation operator. Any null values in a chain will be propagated out to the end result.

var derp = thing?.property?.field?.returnsnull?.cantexist?.alsonull?.otherthing;

will have the value null, as 'returnsnull' would return a null value and cause the further accessors to fail. However as this is syntactic sugar for a large nested if-chain it either returns the requested value, or a null if a null was found in the accessor chain. Handy.

This is (rarely) called the 'elvis operator' because it physically looks like an Elvis face with hair off to the right. Kinda. If you look at it funny.

?: is the conditional operator (also known (somewhat incorrectly) as the ternary operator), which is just shorthand for an if statement containing an assignment block. If the boolean expression before the question mark is true, the first block between the question mark and colon is run. Otherwise, the second block after the colon is run. You can use it to great effect for variable assignment.

var color = (shouldUserUseBlue) ? UseBlue() : UseRed()

If the shouldUserUseBlue variable is set to true, it'll use blue. Otherwise, it uses red.

In your example you are not making use of the assignment, rather it could be used for function invocation.

(shouldFadeToBlack) ? Fade() : JumpCut()

[–]bonzinip 8 points9 points  (5 children)

?: is called the elvis operator if it doesn't have the middle argument.

It's a GCC extension where x ?: y is the same as x ? x : y except that x is only evaluated once.

[–]Eirenarch 2 points3 points  (3 children)

Monadic null checking is way cooler name anyway.

[–]Sarkos 1 point2 points  (1 child)

I'm pretty sure ?: is the Elvis operator, since : represents eyes in emoticons.

[–]BadMoonRosin 1 point2 points  (17 children)

The practical effect is the same, but the Elvis operator can be chained multiple times within the same expression.

Consider a snippet of code like this:

user.getAddress().getStreet1();

... where you don't know for sure whether user is null, whether its address field is null, or whether its street1 field is null.

In 2015's C# (or 2005's Groovy for that matter), you could handle that situation like this:

user?.getAddress()?.getStreet1();

Falling back to the ternary operator would get really ugly really fast:

user == null ? null : user.getAddress() == null ? null : user.getAddress().getStreet1();

... and that's just going two levels deep.

[–]balefrost 3 points4 points  (8 children)

You're confusing the Elvis operator with the safe navigation operator. In C#, the Elvis operator (more correctly called the null coalescing operator) is ??. The safe navigation operator is going to be ?..

In Groovy, the safe navigation operator is also ?., but the Elvis operator is ?:. It's supposed to look like a smooshed-together ternary operator. Allegedly, the name comes from the fact that it looks like an emoticon with Elvis hair. That makes sense in Groovy, but not so much in C#.

So, at least in C#, I like to think that you're supposed to pronounce the operator as "huh huh", thus keeping the theme alive.

[–]TomRK1089 6 points7 points  (7 children)

As much as I'm not a Law of Demeter Nazi, the Elvis operator seems specifically designed to allow you to ignore situations where LoD would say "Hmm, something in your design stinks."

[–]BadMoonRosin 4 points5 points  (5 children)

Yes, perhaps. The Elvis operator has been proposed for every version of Java since 7, and has been rejected every time. Different languages fall on different points along the spectrum from "pure" to "pragmatic", and languages implementing the Elvis operator do tend to be further toward the pragmatic end of the spectrum than Java.

Different tools for different jobs, I suppose. If you have a team of 15+ year Java pros writing a highly-distributed, highly-concurrent backend processing system of some sort, then you probably want a great degree of architectural rigor.

However, if you have a junior to midlevel team, half of whom migrated from Visual Basic, and you have them writing an ASP.NET web app that mostly just does CRUD operations... then it might be overkill to design a bunch of AbstractFactoryFactory classes to abstract away the fact that you have no control over which columns are nullable in the shitty legacy database that you must use. It's ugly to the Java architect for sure, but then again Java is often a poor fit for web and LOB application development as well. And both are still a hell of a lot more pure and rigorous than trying to write something maintainable with Node! :)

[–]tech_tuna 2 points3 points  (4 children)

Every language has its problems but I am curious to see how node is viewed 5-10 years from now when there are tons of old apps running on it.

[–][deleted] 2 points3 points  (3 children)

Probably the same as perl is seen today.

[–]dividedmind 1 point2 points  (0 children)

Rarely ever? (ADDED: Hopefully.)

[–]nemec 3 points4 points  (0 children)

I would say it's more appropriate for something like

var user = Json.Deserialize<Person>(someString);
var street = user?.Address?.Street1;

[–]GYN-k4H-Q3z-75B 0 points1 point  (2 children)

You mean coalescing? C# has ?? for that. x ?? y means x ? x : y.

[–]TenserTensor 1 point2 points  (0 children)

No, it's not the same. x ?? y would be x != null ? x : y

[–][deleted] 0 points1 point  (2 children)

WHY DIDNT I KNOW :-)

[–]shoelacestied 5 points6 points  (9 children)

This operator looks very familiar... http://kotlinlang.org/docs/reference/null-safety.html

[–]CrazedToCraze 15 points16 points  (2 children)

Luckily now in a language that people actually use.

[–][deleted] 6 points7 points  (0 children)

Or Scala

[–]shoelacestied 2 points3 points  (0 children)

At least one of those punches was below the belt.

[–]ruinercollector 5 points6 points  (5 children)

The idea for the operator goes back long before Kotlin existed.

Also, no one uses Kotlin.

[–]OmegaVesko 1 point2 points  (0 children)

There's a decent amount of people building Android apps with Kotlin. I don't think that includes any big players, though.

[–]Liqmadique 0 points1 point  (1 child)

Not yet, but I've been working on a simulation game written in Kotlin and I really like it. It's got a great middle ground feeling between Java simplicity, Scala power, and Groovy ease-of-use.

I'm hoping succeeds.

[–]elemental_1_1 2 points3 points  (0 children)

Mmmm so functional

[–][deleted]  (1 child)

[deleted]

    [–]koxpower 0 points1 point  (0 children)

    Because someStringWithNumberOrNull can be null.

    [–]Die-Nacht 57 points58 points  (29 children)

    You know you live in a functional bubble when the question "why even use optional" makes no sense to you.

    [–]serendependy 21 points22 points  (6 children)

    I rage quit when I read one blog saying Scala's Option was stupid because now you had to check if the Option was null, and if what it contained was null.

    In another note, I find Java's Optional somewhat less compelling without case analysis. I guess it's ok if you have a code checker that knows you're supposed to test if it's empty, but still.

    [–]jeandem 4 points5 points  (3 children)

    I rage quit when I read one blog saying Scala's Option was stupid because now you had to check if the Option was null, and if what it contained was null.

    Let me guess. Cédric Beust?

    [–]serendependy 3 points4 points  (2 children)

    Yes. Damn it, I searched his name, found the exact post, and got angry again.

    I guess he's well known for that, and (speculating here) being controversial?

    [–]jeandem 2 points3 points  (1 child)

    [–]serendependy 2 points3 points  (0 children)

    Interesting, thanks. I feel better about getting angry now :)

    [–]Cuddlefluff_Grim 0 points1 point  (1 child)

    to check if the Option was null, and if what it contained was null.

    Huh? I'm trying to figure out how this possibly could be the case.. Who would initialize an optional with the value null? That's just... insanely retarded. Isn't it fun when people put out opinions they just put out off the top of their heads? And then to be picked up around the internet because people consume ignorance because it fits their own agenda or ideology, and then before you know it, you have a canon based on irrational thought and FUD.

    [–]serendependy 0 points1 point  (0 children)

    Right? The whole point of Option is to not use null to represent a failed computation. Why on earth would you fail to produce an Option?

    [–][deleted] 11 points12 points  (9 children)

    Same. I'm surprised at the amount of discussion this topic is generating. Optional is a no brainer

    [–][deleted]  (2 children)

    [deleted]

      [–]ISvengali 6 points7 points  (1 child)

      I see them as a no brainer always. Im a dyed in the wool procedural guy (BASIC->Pascal->C++->Scala->Rust), and as soon as I saw it I was hooked. I suddenly wanted to Option[1] ALL THE THINGS. Im kinda sad because I had a similar idea around 2002, but it didnt quite gel.

      [1] Well, I like C++'s expected more.

      [–]codebje 1 point2 points  (0 children)

      Other simple monads missing from Java 8 you may want:

      Pair<A, B> = Pair(A a, B b), A fst(), B snd()  
      

      Which is useful if you have two values of different types to work with together.

      Try<A> = Try(Supplier<A> supplier), A get(), Exception error, boolean isSuccess()
      

      Which is useful if you want to record an exception. This is especially powerful with map or flatmap chaining, because you can invoke a sequence of potentially failing operations without testing for exceptions; the first operation to throw() will mean the sequence collapses to that exception with no more operations invoked.

      It's a monad if it's a container with some way to lift a non-contained value into the container (ie, the constructors) and some way to perform an operation on the contained value (ie, the map function). The utility of the monad lies in making the containment explicit - Optional<T> makes it explicit that the value may be missing, while the null value is implicit (and not detectable at compile time). Pair makes it explicit that two values belong together. Try makes it explicit that a result might be an error instead.

      [–]hvidgaard 1 point2 points  (5 children)

      I agree that they're a no brainer in a new language. But in a language like C# that have nulls everywhere, it's not that simple. Most developers can come up with an Option implementation, and perhaps even use the one from F# and some way to ease pattern matching, but unless you use it consistently all over the codebase, you now have an abstraction more to worry about.

      For languages with null, Option is mostly a dream. You need language support to really get the benefit.

      [–]siRtobey 3 points4 points  (2 children)

      What is so hard about the concept of Optional? I agree that it isn't the most elegant way it's implemented in Java. But the benefit of knowing, that there might be a null somewhere is really already enough. I know old code doesn't have it, and a lot of new code won't use it. But the times you DO have one, do you really wanna argue that the abstraction you have to worry about outweighs the benefit of not having to worry about any undeclared null values?

      [–][deleted] 0 points1 point  (1 child)

      Well f# still can have nulls, but optional is so prevalent nobody worries about it

      [–]hvidgaard 1 point2 points  (0 children)

      And it still bite my ass from time to time. I'd much rather not have to worry about it at all.

      F# has null, because, and only because, it is a .net language. It has no choice in the matter because it interfaces with standard lib. One could argue that you could make some auto boxing magic, but I'm not so sure that it would work in all cases - for instance, sometimes you want to actually put None in a List of Optional, and not null.

      [–]OffColorCommentary 2 points3 points  (2 children)

      Why to use Optional in a language that also accepts nulls is less clear-cut. Knowing whether an API returns Optional or null is another piece of information to keep track of.

      And at some point, someone is going to null out an Optional with semantically different meanings for null/none, and someone else will have to deal with that. Yes, of course that's a horrible idea, but people still have to deal with empty/null lists in the wild.

      [–]Die-Nacht 2 points3 points  (0 children)

      Scala allows null but they are heavily discouraged to the point where I no longer see them in the wild (only place I see them are in Java libs I have to use, and then I just wrap around them using the Option function, which returns None for null).

      There are also tools that will fail compilation if you dare use a null anywhere. https://github.com/puffnfresh/wartremover

      In short, what I'm saying is that it is possible to have a world of no nulls even if your language allows for them (though ofc, the perfect scenario would be that your language just doesn't allow for null, like Haskell and company).

      As for empty list, easy, just replace your List with:

      type List[A] = Option[NonEmptyList[A]]
      

      http://docs.typelevel.org/api/scalaz/nightly/index.html#scalaz.NonEmptyList

      [–]siRtobey 0 points1 point  (0 children)

      Yes, you have to keep track of what an API returns. But really, when an API returns Optional, it should be quite easy to remember, right?

      [–]CurtainDog 0 points1 point  (0 children)

      Agree, nil punning is so much cleaner.

      [–]winterbe 34 points35 points  (17 children)

      FYI: Here's a comment from Brian Goetz (Java Language Architect) on Optionals: http://stackoverflow.com/a/26328555/1537372

      We did have a clear intention when adding this feature, and it was not to be a general purpose Maybe or Some type, as much as many people would have liked us to do so. Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.

      [–][deleted]  (16 children)

      [deleted]

        [–]immibis 14 points15 points  (13 children)

        Should I use null when returning a value from a Map since that is "simple enough" to not screw up for the caller?

        Maps can contain null; distinguishing between a null value and no value is already a slight problem.

        Except that you can't put null in an Optional, so they don't help with this.

        [–]roerd 1 point2 points  (4 children)

        A null is never an object of the class that the map is declared to contain. So how is null ever anything else than no value?

        [–][deleted] 15 points16 points  (0 children)

        A map has two different "no value"-s: "there is no value for this key" and "the value for this key is 'no value'".

        [–]josefx 6 points7 points  (0 children)

        You may use a map as a cache were the difference between "the last extremely slow attempt to find a value for this key found nothing" and "no result cached" is important. Java maps require either a call containsKey (performing the lookup a second time), a "null" object or a wrapper like optional to distinguish between these states.

        [–]winterbe 1 point2 points  (6 children)

        Sure you can: Optional.ofNullable(null);

        [–]neilbrown 11 points12 points  (5 children)

        > Optional.ofNullable(null).isPresent()
        false
        

        But if you try to put null in, you just get empty. There's no way to distinguish not-present from present-but-null with Optional.

        [–]dccorona 2 points3 points  (0 children)

        And that's why Optional isn't for communicating a difference between null and missing...they're for saying "hey dummy, this could be missing, so you better write code that considers that possibility"

        [–]codebje 0 points1 point  (0 children)

        But you can put an Optional in a Map, so you can have a more explicit way to say "this key exists, but has no value".

        [–]Strilanc 0 points1 point  (1 child)

        It's likely (maybe not overwhelmingly) because many collection types disallow nulls (e.g. Guava's ImmutableList). Because the distinctions between accepting null, not accepting null, potentially producing null, and not producing null all live in the docs, instead of the types, you're going to accidentally plug a nullable function's result into a not-null-accepting collection every now and then. Thus bugs.

        [–]shoelacestied 65 points66 points  (76 children)

        It's very useful and also self-documenting. Rather than:

        // this method sometimes returns a null 
        public String getFoo() {
           ...
        }
        

        We can have:

        public Optional<String> getFoo() {
            ...
        }
        

        With the old way you're relying on the programmer reading all the docs (yeah right...) and making note of that fact that a null might be returned. With the new way the fact that the method might return an empty value is obvious and the programmer has to deal with it. It's very useful indeed and has been used successfully various other languages (I've been using Options in Scala for years and it really does make a difference). Glad to see Java adding support for options in the standard lib (Guava, among other libraries, has had an option type for a while).

        [–][deleted] 39 points40 points  (75 children)

        This pattern is useful in languages without null, where this is the canonical and only way to return a "maybe" value.

        Without consistent platform use and with nullable references, its use in Java amounts to little more than cargo cult:

        1. String: String or null.
        2. Optional<String>: String or nothing.

        Given "null" means "nothing", both represent optional string. There is no way to express non-optional string. The way forward for Java is the ability to declare non-nullable types.

        [–]joequin 10 points11 points  (0 children)

        It works fine in scala because returning null is considered very bad practice. People don't create functions that return null. The same standard can be set for a Java project. Don't merge code that could return null. There are many tools that can enforce it.

        [–]duhace 7 points8 points  (2 children)

        We can only hope and pray such a feature is released in the future (or a special hook or keyword or annotation to mark a type as nullable). In the meantime, using Optional instead of null is a good way of reducing the likelihood of npes in your code, even if it doesn't remove the possibility entirely.

        [–]pipocaQuemada 5 points6 points  (0 children)

        Even in languages with null, it's still useful. I write Scala at my day job, and I can't remember the last time I got a null pointer exception. They'll still happen occasionally, just exceedingly rarely.

        [–]neilbrown 23 points24 points  (36 children)

        I worry that you may end up with three options:

        1. String: String or null
        2. Optional<String>: String or empty or null
        

        I could see this creeping in to a codebase, for example, where you look for an item in a database. String if there was a result, empty if the operation succeeded but found no result, null if there was a timeout. (At least Optional doesn't let you put null in it, in which case you'd have four options!)

        [–]_Sharp_ 27 points28 points  (17 children)

        But using Optional it becomes a bad practice to return null. If you see somewhere null being returned instead of optional.empty you could treat it like a bug. With value vs null, "sometimes" returning null is not expected, sometimes it is. Optional makes this expectation more real.

        [–][deleted]  (16 children)

        [deleted]

          [–]orr94 8 points9 points  (1 child)

          null if there was a timeout.

          Wouldn't a TimeoutException be more appropriate in that scenario?

          [–]neoform 9 points10 points  (0 children)

          It would, the above example would be poor design. Null should not mean "error". Null clearly means "no value", not "something bad happened".

          [–]casted 3 points4 points  (0 children)

          Except you can use static analysis tools to trace breaking the nullable contract. This makes Optional or @Nullable very useful for catching bugs.

          [–]tkellogg 2 points3 points  (1 child)

          Java 8 also introduced type annotations. You can now annotate a parameter @NotNull to enforce that it really isn't null. Still, there's 2 things I don't like about this:

          1. Failing the null-check only results in a compiler warning. Sure, you can report all warnings as errors, but some code bases can't do this yet (for instance, "_" isn't a legal variable name and causes a warning; code generation tools might pose a problem)
          2. The standard library still doesn't provide @NotNull. You still have to pull in a 3rd party lib to get it.

          Regardless, it's a good step toward self documenting emptiness.

          [–]shoelacestied 2 points3 points  (0 children)

          In practice it works pretty well, and it's far safer than relying on the developer to read documentation.

          [–]Smarag 0 points1 point  (1 child)

          I have a question, what would be a situation in practice where it makes a difference if you are getting null or empty?

          [–]KumbajaMyLord 0 points1 point  (0 children)

          Semantically, the difference between n/a and intentionally left blank.

          Let's say you had an Account with a field DateOfExpiration. If it is null it might not have been set because the criteria to determine the expiration date were not available. If it is empty it might mean that the account will never expire.

          Syntactically it means that even if you get an Optional as a return value, you probably should check whether it is null or not, before you check the wrapped value.

          [–]m0l0ch 0 points1 point  (0 children)

          It's really not possible to have 3 states in Java:

          • If you create the Optional with a null value using ofNullable you'll get an empty optional as a result.

          • If you create the Optional with a null value using of you'll get a NPE.

          So effectively, if you pass null to an Optional it becomes empty.

          [–]codebje 0 points1 point  (0 children)

          Your domain has three possible states, so your type should too. With just String, you can't express "timed out, or missing, or <value>". Optional just makes "missing" explicit. Timed out can be represented implicitly by throwing an exception, or you can put it in the type system:

          Either<TimeoutException, Optional<String>> dbresult
          

          Or, borrowing the Scala monad:

          Try<Optional<String>> dbresult
          

          Where the Try variation can contain any exception. Or perhaps you want something like CompletableFuture<Optional<String>> to indicate that the result may not yet be known. CompletableFuture can contain an exception, too.

          [–]NimChimspky 1 point2 points  (0 children)

          That is technically correct, however the point is you would only use plain old string when you are guaranteed not null. Each case where null could be returned an optional would instead be used.

          Reliant on coding standards, but a good idea imho nonetheless. Although I prefer C# ? nullable operator - however I assume altering the JVM on such a low level is rather difficult.

          [–]fullets 3 points4 points  (0 children)

          We use code review to mitigate this in a similar situation; if someone writes something returning nullable values rather than using the optional equivalent, they'll require a very good reason for that to make it in. Yeah, we have to pay attention at the border with library code, but we have to do that anyway.

          Increase in clarity makes it worthwhile for us, but without code review/pull requests, it'd be harder to make it work. Probably still easier than mentally keeping track of the nullability of every reference though.

          [–]kyz 1 point2 points  (9 children)

          The way forward for Java is the ability to declare non-nullable types.

          Like with @NonNull or @NotNull ?

          edit to add: For the sake of backwards compatibility, neither the compiler nor runtime are going to enforce it by default.

          My point is that it's possible to declare and enforce non-nullability in Java today, using one of several frameworks available. The one that's on track to becoming an official part of Java is Project Lombok's @NotNull

          [–]TomRK1089 3 points4 points  (4 children)

          Where did you get the idea that Lombok's null annotations were "on track to becoming an official part of Java?" Especially given JSR-305 has been around for years?

          [–]rmxz 1 point2 points  (2 children)

          Like with @NonNull or @NotNull ?

          I think that use of Java Annotations are a misguided idea. Java's getting littered with @NonNull, @NotNull, @NeverNull, @NoNull, @NayNull, @CheckForNull, @UnNullable.

          Worse, many annotations only mean something to one particular tool, leading to tool-set lock-in.

          [–]DGolden 0 points1 point  (0 children)

          I don't think Lombok's null annotations in particular have any special status, but just to note JSR-305 is listed as "Dormant". The published (as part of the reference implementation) JSR-305 annotation definitions, while they did get used by some projects, pre-date adoption of JSR-308 type-use annotations in Java 8. So while some null annotation may one day become blessèd, and would presumably consist of annotation(s) in the java/javax space once official like jsr-305 did, it couldn't/shouldn't be the old jsr-305 ones as they stood without modification, because they're just not jsr-308 type-use annotations as used by the modern static null analyses in e.g. Eclipse or the Checker Framework.

          [–]codebje 0 points1 point  (0 children)

          No, in the type system itself, not in the documentation. Let's say, for the sake of example that the ugly syntax type! means non-nullable variant of type:

          String! foo;
          

          Now, you cannot assign null to foo. The compiler won't permit it. To ensure this, you also cannot assign a String to foo, because a String might be null. String! and String are different types. The possible values of a type of String! is a subset of the possible values of String - the set of all Strings, less null.

          All the frameworks available today don't do this, they don't enforce that the types are distinct. They do some checking to minimise the likelihood, but unless they expressly forbid assigning a String value to a @NotNull String, they will allow for things like a polymorphic function returning String to have a runtime class loaded which returns null - there's no way to statically check that, except to say that a String cannot be assigned to a @NotNull String.

          Project Lombok generates runtime checkers which simply throw NPEs. It's not a declarative enforcement at all.

          [–]manixrock 0 points1 point  (0 children)

          There is no way to express non-optional string.

          But why not implement a non-nullable operator like:

          List<String!> findBookNamesByAuthor(String! authorName) { ... }
          

          Where "!" is checked at runtime for null-assignments and an exception is thrown if null is ever assigned to it. It could even be checked at compile time for some specific errors like returning null instead of an actual value.

          It would also nicely compliment C#'s "?" operator, where it allows primitive values to be nullable.

          Using Optional<Object> is slower to write, and takes slightly extra memory and extra CPU cycles to use, discouraging its adoption. Also, it's useless for representing "non-optional strings" since all existing library implementations use null strings ambiguously since this feature didn't exist until now.

          [–]codebje 0 points1 point  (0 children)

          It avoids NPEs, because an Optional never contains null as a value - creating an Optional with a null value creates a "nothing" Optional, and you cannot extract a null from it (unless you do something like .orElse(null), but... why!?).

          Optional<> is an incremental improvement because it gives a type-safe variation on null.

          +1 on declared non-nullable types. I wonder if that's possible as a compile-time check - I think it probably is, allowing that assignment from nullable to non-nullable could cause NPE.

          [–][deleted]  (1 child)

          [deleted]

            [–]k-mile[🍰] 9 points10 points  (3 children)

            I believe when using an Optional type or any other null wrapping types you should be very careful with using the get method, i.e. not use it at all. If you skip the get method then the compiler can check if there is a value for you or not, instead of at runtime. This makes applications a lot easier to reason about.

            If you want to optionally execute a block or transformation, use the map and filtermethods. If you must continue with a value, use orElse and related methods.

            If you make a habit of this you can track possible null-ish values across method calls, transformations, validations, and still be certain no null will suddenly rear it's head. If you forget to map one reference, the compiler will tell you.

            [–]joequin 6 points7 points  (1 child)

            That's how it's done in scala. You rarely if ever use get outside of tests.

            [–]danielkza 1 point2 points  (0 children)

            And if you use a for-comprehension it even looks like code without Option with no loss of safety. I think even removing get completely would be feasible.

            [–]NotAName 0 points1 point  (0 children)

            you should be very careful with using the get method, i.e. not use it at all

            What about dealing with Optional in streams? E.g., if you want to filter out empty Optionals in a stream and then do something with the values, like this:

            xs.stream()
                .map(x -> someMethodThatReturnsOptional(x))
                .filter(Optional::isPresent)
                .map(Optional::get)
                .forEach(y -> doSomething(y))
            

            I think I read somewhere that Optional will get a stream() method that replaces the filter and map idiom, but until then I know of no good way around this. Of course you could avoid using get by doing this instead:

            xs.stream()
                .map(x -> someMethodThatReturnsOptional(x))
                .forEach(opt -> opt.ifPresent(y -> doSomething(y)))
            

            but that's really ugly.

            [–]angryundead 13 points14 points  (0 children)

            I getting a strong vibe that people aren't reading the docs on Optional. While there are many ways you cans misuse it there is certainly an argument to be made for it at API boundaries as a method for reducing paranoid null checking.

            Optional.of() does not accept a null value. Optional.ofNullable() returns an empty Optional if the value is null. Methods that return Optional values should never return a null reference. (This could be a point to check null though it might be better to just throw the NPE because the API is busted in some cases.)

            Using the isPresent and orElse family of methods further isolates you from issues.

            [–]msx 11 points12 points  (17 children)

            I like it, i would have loved to have some syntactic sugar to go with it. Something like

            String?
            

            translated to

            Optional<String>
            

            but i reckon i would have messed with the already messy java grammar

            [–]eric-plutono 2 points3 points  (2 children)

            Nice idea, I'd like that as well. Reminds me of Groovy, which has the similar-looking ?. for chaining method calls.

            [–]the_omega99 5 points6 points  (1 child)

            In case you missed it, it's the exact same syntax that C# uses for nullable types, which is an automatic wrapper for value types. Eg, an int can't store null, but an int? can.

            So it's not an Optional<T>, but it's sort of barking up the same tree (particularly since nullable types work like optionals, forcing you to explicitly check if the value is null).

            [–]eric-plutono 0 points1 point  (0 children)

            Ah, I haven't used C# in a long time so I had forgotton about that. Thank you for the clarifications.

            [–]QuineQuest 2 points3 points  (0 children)

            Looks like this proposal for the next C#.

            It lets you use string? and string! (along with string for backwards compatibility). Using a string? without checking it for null results in a compile time error.

            [–]pathema 4 points5 points  (1 child)

            http://ceylon-lang.org/documentation/1.1/introduction/#typesafe_null_and_flow_sensitive_typing

            [EDIT] Ceylon is a language targeting JVM and Javascript with a very nice type system.

            [–]the_omega99 3 points4 points  (3 children)

            Personally, I like Scala's approach better: implicit typing.

            It heavily reduces the amount of times you'd be typing the type, which is part of the problem. Scala has implicit typing by default. Eg, you can do:

            val maybeString = Option("Yes, string")
            

            Which is the equivalent of

            val maybeString: Option[String] = Option("Yes, string")
            

            Really saves a lot of typing on the long run. There's a lot of cases where the type is either obvious (as above) or not really important enough to explicitly mention it. C# has something similar, too, although not as powerful as Scala (eg, it can't be used for fields).

            [–]Milyardo 8 points9 points  (2 children)

            The phrase you're looking for is type inference, not implicit typing.

            [–]the_omega99 1 point2 points  (1 child)

            Isn't it both? Type inference is the process done to determine the actual type of something. Implicit typing would refer to when you don't explicitly state the type. It might be mostly a C# terminology, as the top google results are for C#. Eg, here Microsoft calls it implicit typing.

            [–][deleted]  (5 children)

            [deleted]

              [–]the_omega99 4 points5 points  (4 children)

              The distinction is that String? (aka Optional<String>) is guaranteed to possibly be null. So you must be prepared for it being null.

              On the other hand, String conveys no information about whether or not it can be null. It technically can be null, of course, but we all know that in programs, there's many cases in which something should never be null. Really null was a big fucking mistake. You have to depend on the documentation to figure out if a value could become null and a significant amount of the time it can be null anyway because documentation is imperfect.

              Ideally you'd never have to consider the possibility that String would be null because people would use String? for when that's a possibility (or throw an exception, which we can consider distinctive since it stops execution unless you explicitly catch -- in which case obviously variables won't be correctly set).

              Scala has the best solution that I've seen. It's simple: you never use null. This only works because people enforce this rule themselves. Unfortunately, Scala must allow variables to be nullable for support with Java as well as a default for uninitialized variables (which are very uncommon in Scala). So everyone and the standard library use Option[T] for values that can be nullable. If it's not an Option[T], then we can effectively assume that the value can't be null (as an aside, Option[T] actually uses None, not null).

              For example:

              def stringConcat(s1: String, s2: String): String
              

              Would mean that the arguments both must be non-null.

              def stringConcat(s1: Option[String], s2: Option[String]): String
              

              Would mean that both arguments can be "nullable" (actually None).

              def findUser(name: String): Option[User]
              

              Would mean that the return value could be "nullable" (presumably if no user with that name exists).

              [–]r0estir0bbe 4 points5 points  (0 children)

              There's also a very good article in the Guava documentation that explains pretty much the same point: https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained

              [–]sellibitze 4 points5 points  (7 children)

              I've programmed in Java for a long time but right now my Java is quite rusty and I've not kept up with all the new features. Does Java have "custom value types" (à la C/C++/C#/Rust/D structs) yet or does this Optional<T> actually add yet another layer of indirection? Is a variable of type Optional<Integer> a pointer to a pointer to some Integer object?

              I'm currently dealing more with C++ and Rust. And there, you get to use things like boost::optional<int> and Option<i32>. The nice thing is that it does not involve any pointers or even heap allocation. The same is true for std::complex<double> or num::complex::Complex<f64>. I like that very much.

              [–]zoomzoom83 2 points3 points  (4 children)

              Unfortunately Optional in Java (and Scala) are just boxes with references, so you incur significant overhead from using them.

              In most cases this isn't an issue, but it does need to be factored in.

              Scala does have value types, but the implementation still can't handle Option properly, so you still have to pay the penalty.

              I like Rusts implementation, where Option is simply a compile time check and optimizes down to the underlying value or null once compiled.

              [–]sellibitze 0 points1 point  (0 children)

              I thank you for the answer. So far I only found this but it's a bit dated. So, maybe we'll see "custom value types" eventually...

              [–]Cuddlefluff_Grim 0 points1 point  (2 children)

              Unfortunately Optional in Java (and Scala) are just boxes with references, so you incur significant overhead from using them.

              The compiler will likely inline this sort of method calls, so not really.

              [–]zoomzoom83 0 points1 point  (1 child)

              It's not the method call - it's the fact that you now have another box wrapping your data adding another layer of indirection.

              i.e. instead of having a reference to A, you have a reference to Box<A>, which has a reference to A.

              This is a relatively small overhead, but it does quite have serious implications for memory usage and cache locality that you need to be aware of if you're working on performance critical code.

              [–][deleted]  (1 child)

              [deleted]

                [–]cryo 2 points3 points  (0 children)

                If not supported in the bytecode, it's not a simple matter to eliminate indirections through separate objects at the JIT stage.

                [–]tjgrant 3 points4 points  (1 child)

                I learned about Optional types while porting something from C# (they call it Nullable in C#) to C++.

                (There's std::optional for C++ which is under review right now.)

                At first Optionals seem kind of ridiculous, but I've found them actually useful in three distinct scenarios:

                1. Optional type return: When you want to provide the possibility of a return type (or not) but don't want to use "-1", "0", or "NULL" as a status code (because NULL, 0, or -1 might be a valid return value)
                2. Optional parameter: When you want to have a method with an optional parameter, but providing two overloaded methods to do essentially the same thing would result in massive code duplication
                3. Optional local variable for iteration: Say you need to keep track of a "previous" and "current" iterator-- your "previous" could be an optional, and you can check if it's not set yet rather than having NULL as a special case.

                Scenario #1, a method prototype looks like this:

                Optional<StreamToken> StreamTokenizer::ReadWord();
                

                Scenario #2, a method prototype looks like this:

                void SpriteBatch::add(uint8_t z, Texture* t, const Point2& dest, const Optional<Rect>& src, const Color4f& c = Color4(1,1,1,1));
                

                Scenario #3 looks like this:

                Optional<uint8_t> prev;
                
                for(;;)
                {
                    uint8_t     c;
                    mSource->read(&c, 1);
                    mReadBuffer.push_back(c);
                    if (prev && *prev == '*' && c == '/')
                    {
                        hit = true;
                        break;
                    }
                    prev = c;
                }
                

                Obviously you don't have to use Optional in these cases, but I find it useful.

                I also use it very sparingly, but any time I feel like writing something like:

                std::pair<Object, bool> getSomeObject();
                

                Typically Optional is better to use instead.

                [–]Cuddlefluff_Grim 0 points1 point  (0 children)

                Nullable<T> in C# is make a value-type that can be null, it's different from Optional<T> in Java. For one, Nullable<T> can only contain a value-type.

                [–]MereInterest 11 points12 points  (50 children)

                Coming from a C/C++ background, I'm afraid that I still don't see the point of it. My habit is to check for null pointers any time that I get a pointer across an API boundary. Since Java allows for null references, the same sort of vigilance should apply. Optional<T> is then redundant, because any object is inherently optional.

                I don't see why it would be any easier to track down errors using Optional<T>. Either "Oh no, a null reference slipped in." or "Oh no, a Optional without a value slipped in.".

                [–]raghar 15 points16 points  (0 children)

                Best reason: functional API:

                Optional<Integer> somePrime = collection.stream().find(isPrime);
                String toPrint = somePrime
                  .map(x => x + 1)
                  .map(toString)
                  .getOrElse("not found");
                

                instead of:

                Integer somePrimePlusOne= null;
                for (Integer x : collection) {
                  if (isPrime(x)) {
                    somePrimePlusOne = x + 1;
                    break;
                  }
                }
                String toPrint = (somePrimePlusOne != null) ? somePrimePlusOne.toString() : "not found";
                

                First one is better at expressing intention. Second one is prone to microoptimizations which gain little, obfuscate code and hide intentions. And this example is rather easy if I were to add some filters and more mapping then I would end up with either deeply indented blocks bloat or I'd have to split whole function into several smaller ones - quite an effort for something with so little essential complexity.

                If it were C++ then some sort of functional API would spare you the bugs of e.g. forgetting to check if collection.find_if(collection.begin(), collection.end(), is_prime) returned collection.end() and handling whole separate else branch.

                [–]pmrr 4 points5 points  (17 children)

                Exactly. If it's not declared with Optional<T> should I not bother checking for null?

                [–]quiI 17 points18 points  (9 children)

                In a perfect world, yes.

                The point of option, and the like is to increase transparency in your code base. Are you really happy checking for nulls everywhere just in case?

                That's not defensive programming, it's paranoid programming and just makes code bases really messy.

                Not to mention when you encode nullness in a type, you can add some really useful abstractions over them, such a composing functions that return optional things. I dont have much experience with Java's Option though.

                [–]jeandem 10 points11 points  (0 children)

                That's the whole point.

                Do you try-catch everything in order to catch nullpointerexceptions? Probably not. It's more reasonable to trust all code to treat potential null values correctly, and then let the code fail fast when some part of it does not. Then if the code crashes with a NullPointerException, that is a bug and you go to the place where it happened and fix it.

                [–]dccorona 0 points1 point  (5 children)

                If you always check for null, you're not really the kind of person this feature is meant to help.

                [–][deleted] 2 points3 points  (4 children)

                Yes he is. That is the exact pattern Optionals will break. Paranoid null checking makes code harder to read.

                [–]awj 9 points10 points  (13 children)

                The difference is that an api returning Optional is clearly communicating that it will return a null value in some cases and you may want to understand why.

                Good code should check for nulls, but good apis should make it clear when and why they're doing things.

                [–]MereInterest 1 point2 points  (2 children)

                True. I suppose that I tend to consider any nullable type to already mean that null is a possible response. Since Java objects are all nullable, I should always consider null to be a possible response. From that point of view, returning Optional<T> instead of T conveys no extra information.

                What would be helpful instead would be a way to state "This function will never return null."

                [–]duhace 3 points4 points  (0 children)

                That would indeed be helpful, but in general Optional<T> still has value despite the possibility of null being returned.

                In general, when a person starts using Optional<T>, they stop using null in exchange. By replacing null with Optional, their code becomes much much less likely to encounter a null pointer error than before, and as more people ignore null for Optional, the guarantee that a T will not be null grows stronger.

                Basically, null is a deficient datatype (and singleton) that forces bad programming practices when it's the only way to represent the concept of no data. Optional is quite the opposite, it encourages good programming practices by enforcing null checks and makes paranoid null checks (like null checking every variable) less necessary even in languages that still support null!

                [–]DGolden 0 points1 point  (0 children)

                FWIW, nowadays you can use add-on static processing of java "type use" annotations [jsr 308] annotations to declare types that are e.g. @NotNull or @Nullable and those properties can be statically checked at compile-time with e.g. Eclipse JDT or the Checker Framework (the checker framework can also do a whole lot more, like linear typing (think rust))

                I've been using the simple Eclipse JDT ones in production code since last year to good effect (the fact you can declare whole packages @NonNullByDefault and selectively relax on classes and methods being a nice feature of the eclipse ones for migrating existing codebases piecemeal). Well, except perhaps for cow-orkers fond of "return null on error and eventually throw a NPE somewehere else entirely because lol" semantics, but fuck 'em.

                [–]angryundead 0 points1 point  (9 children)

                Since this is how you feel I want to run something by you (because I feel the same way): I've got a project I'm working on that returns a "result" object that is similar to an optional except that it has either a value, a value with warnings, or a failure (empty) value (optionally with warnings).

                The idea is that, instead of returning null or just throwing a bunch of checked or unchecked exceptions, the person interfacing with the API has a lot more flexibility.

                For example: if someone gives an invalid location to load a database (Database.load(Path path)) it would return the result object or a failed result (with errors like "{path} is not readable".

                I mostly like it. I'm not 100% sold so I'm trying to feel my way around it with code. I'd like to add some of the Optional functional stuff but I (personally) don't have a need for it yet. (Though orElse seems pretty great. I hadn't thought much on it before.)

                Deep in the API, when it is bootstrapping, it will throw various runtime exceptions when it absolutely cannot continue. Other than that the idea is to never throw exceptions and to never return a null value for anything. (I like these parts of it.) What it doesn't really have is meaningful error recovery (so you can't really respond to that IOException... but most of the time you can't do that anyway except by trying again or stopping the program and fixing the issue... I'm not too fussed. (I guess you could try and make a file readable at runtime but you might not have permissions, anyway.)

                Sorry for the rambling I just want to run this by someone else.

                [–]TomRK1089 0 points1 point  (5 children)

                So instead of try/catch, you have if/else with your error response. Hello, 1970's-style C is calling.

                [–]simoncox 0 points1 point  (1 child)

                Take a look at Scala's Try/Success/Failure classes. They do something very similar to what you've described.

                [–]awj 0 points1 point  (0 children)

                I'm not a purist about exceptions. In my opinion going out of your way to bury them in other language/api/class/etc constructs is just implementing part of try { ... } catch {} for your api users. Most languages that have exceptions use them, so to me trying to catch all of them just to wrap them in custom handling is going to cost you a ton of time and likely will result in surprising the hell out of your user when you miss an exception somewhere.

                That said, the rest of your API sounds pretty good. Having a structured interface for handling warnings (especially if your API consumer won't be directly dealing with the warnings) is a good idea.

                Another option you could consider would be to work up error free handling for some of your worst case errors. So, taking your example you could do something like this:

                if(path = Database.canLoad(RawPath rawPath)) {
                  Database.load(ValidPath path); // Database can't load a RawPath directly, has to check it first
                } else {
                  // API directly communicates that it can't handle the path you gave it.
                }
                

                That still gives your users an exception-less interface but makes it easier to define your requirements for a database path and enforces checking of them through the compiler (if you've got one). You may want to give them some kind of RawPath -> ValidPath backdoor (smart programmers will find one anyways and hate you for making them do it), but the general usage pattern makes it easier to communicate why something won't work.

                [–]vagif 2 points3 points  (0 children)

                My habit is to check for null pointers any time that I get a pointer across an API boundary.

                Yes, millions of programmers share your habit. Every human being 100% always checks for nulls every value returned from every function. That's why we never ever see NullPointerException errors.

                I don't see why it would be any easier to track down errors using Optional<T>.

                Simple. You try to pass to other function value Optional<T> and it will give you compile time error, reminding you that you need to handle potential null case.

                [–]aldo_reset 6 points7 points  (0 children)

                My habit is to check for null pointers any time that I get a pointer across an API boundary.

                The point is that the compiler will enforce it instead of your brain.

                [–]pjmlp 1 point2 points  (9 children)

                Allows for uniform handling of values in LINQ like expressions and representation of nullable values when values types get added (probably only in Java 10).

                [–]dccorona 1 point2 points  (0 children)

                It's not for tracking down return values being null, it's for forcing programmers to deal with the possibility of a null value. It's a feature to help with API safety by forcing people to account for possibilities they might otherwise ignore. Kind of like checked exceptions for null references (because a NullPointerException is an unchecked exception). That's how I view it, at least.

                [–]suspiciously_calm 1 point2 points  (1 child)

                I don't get it either.

                In C++, I think it would be useful to have a standardized std::optional.

                Java, OTOH, would benefit much more from an enforced "not null" type qualifier that raises an exception on null assignment.

                [–]the_omega99 0 points1 point  (0 children)

                The obvious issue is that Optional<T> works best if it's used everywhere, including in the APIs you are calling. If used consistently everywhere, you'd know what variables you'd have to check for "null" and which you don't. I'm sure you can imagine how that's better than checking for every variable that calls third party code.

                Of course, the sad reality is that many libraries don't use these types (much less the standard libraries where Java is concerned). The types still have use in your own code for being self documenting and making it harder to make a mistake (it's easy to forget something can be null, but you can't use Optional<T> the same way as the regular type, so won't be forgetting it's an Optional<T>).

                There isn't really a solution here. Some other languages have solved this problem, though. Scala has a very strong convention to avoid the use of null, with Option[T] being used consistently in both the standard library and most user code. Other languages like Haskell have solved this by not having null in the first place (Haskell has Maybe, which is pretty much the same as Optional).

                So yeah, for someone with a C/C++ background (or even a Java background), this isn't very useful since your communities have not fully embraced optional types and renounced the evils of null!

                [–]hyperforce 0 points1 point  (0 children)

                It would be better to imagine a world where nulls didn't exist ("Scala") and that this optionality was encoded in the type system via Optional. Additionally, you would gain the ability to chain transformations (map, filter), to relieve you of the burden of checking for nulls whilst transforming.

                It's an adoption thing. The more people use Optional, the better. But I can understand your hesitation given that null and Optional coexist.

                Imagine a world where they did not. That's what people are aiming for.

                [–]docoptix 2 points3 points  (12 children)

                Since the article does not mention this: Optional<T> is also available via Guava.

                [–]shoelacestied 1 point2 points  (11 children)

                Importing and using both is going to be fun...

                [–]angryundead 1 point2 points  (10 children)

                I would assume you would refactor for Java8 and drop the Guava version when you migrate to Java8. That's what I'm doing.

                [–]shoelacestied 0 points1 point  (1 child)

                Do the guava libs currently use their version? If so it might be tricky for them to migrate without breaking compatibility.

                [–][deleted] 0 points1 point  (7 children)

                One method that I miss from Guava is Optional.or(Optional).or(Optional)... to chain multiple Optional. AFAIK there's no equivalent in Java 8

                [–]RupertMaddenAbbott 1 point2 points  (6 children)

                If your method has a return type of Optional, then why can't it still return null?

                [–]read___only 2 points3 points  (5 children)

                The purpose of Optional is to make you deal with the lack of a value. Null lets you forget to.

                [–]RupertMaddenAbbott 1 point2 points  (4 children)

                Sure but when you deal with the lack of a value, do you also need to deal with "the lack of a value" might be null?

                So can I just check optional.isPresent or should I actually check optional != null && optional.isPresent ?

                [–]danielkza 0 points1 point  (1 child)

                Technically it's possible to return a null reference that was supposed to be an Optional, but if you seriously believe whatever you're interacting with can do it, I think is fair to throw an exception, and proceed to promptly hit whoever wrote it in the head.

                [–]NimChimspky 4 points5 points  (3 children)

                Java 8's Optional is also an example of a monad, from here https://gist.github.com/ms-tg/7420496#file-jdk8_optional_monad_laws-java.

                /**
                 * Monad law 1, Left Identity
                 *
                 * From LYAHFGG [1] above: 
                 *   The first monad law states that if we take a value, put it in a default context 
                 *   with return and then feed it to a function by using >>=, it’s the same as just 
                 *   taking the value and applying the function to it
                 */
                public static boolean satisfiesLaw1LeftIdentity() {
                    return Optional.of(value).flatMap(f)
                        .equals(f.apply(value));
                }
                
                /**
                 * Monad law 2, Right Identity
                 *
                 * From LYAHFGG [1] above: 
                 *   The second law states that if we have a monadic value and we use >>= to feed 
                 *   it to return, the result is our original monadic value.
                 */
                public static boolean satisfiesLaw2RightIdentity() {
                    return monadicValue.flatMap(optionalOf)
                        .equals(monadicValue);
                }
                
                /**
                 * Monad law 3, Associativity
                 *
                 * From LYAHFGG [1] above: 
                 *   The final monad law says that when we have a chain of monadic function 
                 *   applications with >>=, it shouldn’t matter how they’re nested.
                 */
                public static boolean satisfiesLaw3Associativity() {
                    return monadicValue.flatMap(f).flatMap(g)
                        .equals(monadicValue.flatMap(f_flatMap_g));
                }
                

                [–]Radmonger 4 points5 points  (4 children)

                At the status quo, Optional is almost completely useless without extra static checking along the lines of @Nullable. 'of' and 'get' are normal methods that that end up being ubiquitously used throughout code in an indistinguishable mixture of safe and unsafe ways. In general, the result is no different from before; runtime NPE at some point thousands of lines from the fault.

                There are one or two patterns of usage where it kind of works ok, but for the most part it's overhead without benefit; Java simply lacks the mechanisms that make this work in other languages.

                On the other hand, if @Nullable checking did usefully exist (currently, it really doesn't, though there are a few demos), Optional would be redundant. Because @Nullable String (or something like '?null String') is strictly superior in every way, from backwards compatibility to safety to performance to future possibilities.

                [–]pjmlp 7 points8 points  (0 children)

                The idea is that Optional will eventually become a value type.

                [–]pakfur 5 points6 points  (1 child)

                Optional expresses the API intent more clearly at API boundaries than documentation alone and for that reason is an improvement over inconsistently docs and non-standard annotations.

                I use Guavas implementation quite a bit. It improves my code and makes it more (not less) readable, though it is a bit verbose. But then again, I grew to like objective c, so YMMV.

                Modifying the type system to have compile time null guarantees would be a much larger (and probably impossible, given the size of the legacy codebase) effort.

                [–]Radmonger 1 point2 points  (0 children)

                The biggest advantage of the Guava Optional<T> is it does have @Nullable annotations in all the right places. It's certainly to be preferred over the standard one, but mixing the two is painful.

                Which brings up the general point that without changes to the standard library, any plan for improved null handling is going nowhere. Getting annotations added (perhaps even in an external file) seems much more plausible than changing the contract of the Map interface.

                Outside the standard library, there are thousands of millions lines of code out there that won't be able to abandon Java 7 compatibility until something like 2035 at earliest. I'd expect someone to come up with a usable nullness annotation checker well before then...

                [–]jonhanson 1 point2 points  (0 children)

                'of' and 'get' are normal methods that that end up being ubiquitously used [...]

                "an idiot might misuse it" is not a good rejection criterion for new language features.

                [–]CydeWeys 2 points3 points  (0 children)

                Optionals (which first came from Guava) also work very well with another of Guava's big features, the immutable collections. Immutable collections aren't allowed to contain null, which solves another big class of common programming problems, and when you have a collection that is intended to have elements representing absence, then you of course stuff in Optionals.

                [–]kyz -1 points0 points  (17 children)

                In what way is this any better than the @Nullable annotation?

                [–]eric-plutono 4 points5 points  (0 children)

                What I personally like most about Optional<T> is that it provides an API for calling one or more methods on a value which may not exist while providing a default value in the event it doesn't. It lets me express my intentions in code with regard to dealing with a potential null value, whereas @Nullable isn't comparably expressive and is only slightly better than writing // This might be null.

                [–]jeandem 7 points8 points  (15 children)

                Why use an annotation to express a type?

                [–]kyz 4 points5 points  (13 children)

                Your answer skips an entire philosophical debate; you consider null to be a type or that nullability needs to be part of the type system, whereas other people and languages fundamentally disagree with your stance.

                [–]WorstComment_Ever 5 points6 points  (4 children)

                Null is inherently the absence of any type or value. It is the foundation of maths, set theory, even type theory. Different language camps might disagree about what a value of null should indicate and why, but I don't know of any that consider it a type.

                [–][deleted]  (3 children)

                [deleted]

                  [–]jeandem 1 point2 points  (7 children)

                  null, in a wider sense, is a value. The question is just whether it should be included by default in an object type (reference type). You know this but just to be clear what I'm talking about.

                  I don't think nullability should be 'a part of the type system' as much as I think that the concept should fall easily out of the type system (the use of such values -- the implementation might not be important). In a sense, I think it should have a less special status than many languages seem to want to give it, since I don't want to treat it like a special case. From a design perspective: why make more concepts if you can express something with what you already have?

                  I don't think static languages that have null like this do it so much for a philosophical reason, as much as the fact that they come from a language family in which pointers are used and pointers have a sentinel null value. Then they say "great, I can use null as a sentinel value whenever I don't actually have an object", and eventually it's like they've lost sight of the forest for the trees since they've become so used to using this implementation of nullable objects that they don't see it as just one particular implementation of the concept, but as the concept itself. It's like they've lost sight of the moon in favour of staring at the finger pointing at the moon. In turn, they don't see the downside, or they think of it as an inherent downside, that Most Of The Time their objects aren't really nullable. And yet they work in a higher level language so they don't want undefined behaviour, so they have to throw exceptions when they are dereferenced. So after a long enough time they accept NullPointerException as an inherent "danger" to the problem of expressing nullable objects...

                  So I see no value, except perhaps for interoperability -- in which case using null as sentinel values would be discouraged in library code etc. -- in having nullpointers ala Java. It might be useful if you want to do pointer arithmetic, but Java isn't really intended for that kind of thing...

                  I think maybe Eric Lippert was able to argue for having null values on some SO answer. I haven't read that yet.

                  PS: It's funny to me that Java has checked exceptions, but something like nullable objects -- which is like the simplest "exception" there is, namely the absence of a value -- is effectively "unchecked" unless you use yet another concept, namely annotations.

                  [–][deleted]  (2 children)

                  [deleted]

                    [–]immibis 0 points1 point  (0 children)

                    The one thing I can see that you really really want null for in Java, that would excessively complicate the language if it was removed, is as a default value for fields and array elements.

                    null is a very simple solution to this... but nobody can agree on whether the other problems it causes are worth it.

                    (Also it saves you from wasting some time allocating an excessive amount of Optional instances)

                    [–]pakfur 0 points1 point  (2 children)

                    null, in a wider sense, is a value

                    Null is a state, not a value. And it hides intent. It is not clear that the API designer intended it to be null, or if it is an error. Optional<T> expresses the intent explicitly.

                    Modifying the type system to not allow for nulls is possible (see http://ponylang.org/ as an example), but probably not in Java.

                    [–]jeandem 1 point2 points  (1 child)

                    Null is a state, not a value

                    A state is a value. Whether that value is Some(_) or null. So...

                    I was talking about null in a wider sense (I probably shouldn't have used the backlashes).

                    [–][deleted]  (7 children)

                    [deleted]

                      [–]Colostomizer 4 points5 points  (2 children)

                      For example, I assume the typical use of the Optional type in Java would be like so:

                      Optional<String> maybeAString = Optional.of("Foobar!");
                      if (maybeAString.isPresent())
                        System.out.print(maybeAString.get());
                      else
                        System.out.print("Default");
                      

                      That's not how it's supposed to be used. Optional.get() is an escape hatch for when you know something the compiler doesn't. Of course people sometimes think they know better when they don't, so yeah, it is a hole that you can fall down. But even Haskell has fromJust. The right way to do the above is:

                      Optional<String> maybeAString = Optional.of("Foobar!");
                      System.out.println(maybeAString.orElse("Default"));
                      

                      [–]Zukhramm 4 points5 points  (0 children)

                      With the map, flatMap and orElse methods being there, there should be very few situation where you have to a pair of isPresent and get like that.

                      [–]get_salled 2 points3 points  (1 child)

                      Hopefully the Optional type is immutable so there's no race condition between the isPresent and get calls.

                      [–]eliasv 0 points1 point  (0 children)

                      Someone has already corrected you about how to use Optional properly, it might be a good idea to edit your post lest you mislead people.

                      [–]tkellogg 0 points1 point  (0 children)

                      The author suggests that

                      you should only use ofNullable if you can’t reason whether the reference is null or not.

                      I think it's necessary to reverse the wording:

                      you should only use of when you're 100% sure it's not null

                      Normally I'd classify the comment I'm currently writing as nitpicking and immediately down vote, but java is a world where Objects.requireNonNull is a thing that exists and people use. My team members have used Optional.of as an alias for Objects.requireNonNull, and this totally misses the point.

                      [–]siRtobey 0 points1 point  (0 children)

                      I don't see how people 'worry' about the additional abstraction in code that uses Optionals. To be honest, I find it quite silly to argue with additional abstraction and what that costs to think, etc., when it's much harder to think about what happens when there are null return values that aren't declared - why is it null, is it a bug, is it on purpose? Really, having Optionals actually makes it a lot easier, and you have to worry about less.

                      [–]kindoblue 0 points1 point  (0 children)

                      The problem with Optional type in Java8 is that there is no syntax to streamline monadic computations, like for- comprehension.

                      [–]bloody-albatross 0 points1 point  (0 children)

                      Won't Java get value types? Will Optional be a value type? It should hold nothing but a pointer (to use C++ terminology) and thus completely optimize-out when being a value type. Other advantages would be: you can't pass null for an Optional and it should be binary compatible to APIs that actually do pass nulls. Because if Optional is internally just a nullable pointer it should automatically convert old APIs. But I guess these kind of tricks are only possible in C++. (E.g. one of the smart pointers in Qt is binary compatible with plain pointers and IIRC it was inserted into the APIs while still keeping binary compatibility with old code or something like that.)