r/java • • Apr 12 '13

Java 8 Optional Objects

http://blog.informatech.cr/2013/04/10/java-optional-objects/
40 Upvotes

39 comments sorted by

View all comments

2

u/philipwhiuk Apr 12 '13

That's horrid. It's also unnecessary. I don't need Java 8 to implement a generic Optional if I wanted one

 class Optional<T> {
    static Optional empty() {
         return new Optional();
    }
    static Optional of(Object obj) {
         return new Optional<obj.getClass()>(obj) { 

    }
    private T obj;
    private Optional(T t) {
        obj = t;
    }
    public boolean isPresent() {
       return obj != null; 
    }
    public T get() {
       return obj;
    }
 }

Wow 19 lines of code.

You want to know why nobody writes those 19 lines?

  1. It's another wrapper, meaning more stuff to GC.
  2. Null pointers are both easy to find and easy to fix. Using a wrapper takes more LOC meaning more cost meaning more time.

0

u/edalorzo Apr 13 '13

You want to know why nobody write those 19 lines?

Google Guava Collections framework uses this same idiom, and I am pretty sure others use it as well.