1. 15
  1.  

  2. 6

    That with the lambdas makes for a very powerful new set of features in Java 8. It’s almost a new language.

    1. 8

      I played with this today and found it a little awkward. ML-like languages can get rid of NULL because they have pattern matching. In fact, I couldn’t even get it to work. Something as simple as:

      // class field
      public Optional<Character> gender;  
      
      // toString
      return " gender=" + gender.orElse('U');
      

      The point being to return M/F (or whatever other character is set as gender) .. this still returns a null pointer exception, if gender is uninitialized. To initialize it one has to do:

      public Optional<Character> gender = Optional.of('U');
      

      Which really defeats the purpose of using Optional (i.e. to avoid NPEs). I have no control over client code.

      Am I wrong? Am I misunderstanding the expected behaviour?

      1. 11

        That is the expected behavior. Java 8 doesn’t enforce non-nullable references, neither does Scala. Optional is just a design pattern.

        There are other languages, like Kotlin, which have language level support for non-nullable types.

        1. 2

          yes (it’s expected behaviour and it defeats the purpose); it seems like the groovy / c# approach is more pragmatic (i think the elvis operator would do fine here?).

          it seems like a language extension (.?) would be better than a clunky library class here.

          1. 1

            I think to initialize the field you only need this:

            public Optional<Character> gender = Optional.empty();
            

            which is a little better – you don’t need to think of or define a custom value for “unknown”.

            And as others have said, yes, you still have to work around the fact that Java cannot guarantee that an object reference is not null. An API’s use of Optional signals that since the API uses it where possible, it probably won’t ever return a plain null, so you don’t have to bother checking for NPEs from it. But you can still never be sure that you won’t get null – the latest Java hasn’t changed that property of object references.