Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The point of a static type system is to have the language help you out as much as possible to write type-error free code. It can't guarantee that you haven't messed up, but it's supposed to help.

Null ruins that. It's a known source of runtime exceptions, and it is not a compilation error to return null or forget the null-check. It is a compilation error to pretend that an Optional<T> is just a T. The Java compiler is not smart enough to prevent you from doing something silly like calling get() on Optional<T> without checking isPresent() first, but at least it gives you something.

Also Optional has some really nice creature comforts. It gives you the ability to map to compose an Optional<T> with functions that couldn't care less about the Optionality, and it lets you use flatMap to chain successive calls that might fail together, avoiding an arbitrary number of null checks (that you might forget!) in your code.

Frankly arguing against Optional<T> is like arguing against map on lists/streams and saying that for is good enough for you. You can do it, but I think you'd be nuts to work against yourself like that.



Kotlin does it more efficiently. But you wouldn't want it to be an error to use get without calling ifPresent. Sometimes you know that the type system is wrong and that in fact, although this thing is optional, it will in your case always be there. So being able to rapidly convert optionality into an error (we might call it a NullPointerException) is important. Kotlin has the !! operator for that.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: