4 ms·
Wait, javas Optional is a reference type so it can be null? Doesn’t that almost defeat the purpose of it?
by alkonaut 3y ago
Wait, javas Optional is a reference type so it can be null? Doesn’t that almost defeat the purpose of it?
- Defletter 3y agoYup. Your IDE will likely highlight it as an issue, but it's totally legal to return a null Optional. There's nothing special about it, it's just a wrapper class.
- alkonaut 3y agoDid the project to add value types to Java (I’m sure I heard of it a decade ago) never finish?
- Defletter 3y agoNot yet, that's Project Valhalla iirc. It's coming along but hasn't been merged yet. I don't believe it's even a preview feature within the JDK yet.
- steve_rambo 3y agohttps://openjdk.org/projects/valhalla https://openjdk.org/projects/valhalla
- michaelt 3y agoArguably yes, but that doesn't stop people using it. Basically Java had nulls from the start. A decade or so later some people who didn't like nulls introduced their own Optional type, as a third-party library. Enough people liked it that Optional was added to Java's standard library. But as it's just an object, it can be null. Some null avoidance enthusiasts also use third-party @Nullable and @NotNull annotations, which some automated code checking tools will attempt to verify during compile/test.
- paulddraper 3y agoKinda. Every non-primitive is nullable in Java. Adding Optional doesn't/can't change that. You can have a gentlemen's agreement to prefer None to null.
- pgwhalen 3y agoIt doesn’t defeat the problem in theory, but in my experience it does in practice. I’ve never come across an NPE on a nullable reference even in development - it would have to be the result of a really fundamental misunderstanding of the concept. YMMV. Obviously it depends on your teammates.
- mrkeen 3y agoIt gives you the ability to treat nulls as something-to-fix. In a team without Optionals, every time you touch a null that you didn't expect, you have to decide "Is this deliberately null, or was it a mistake?" Without that knowledge, you don't know whether your code should assert against the null, or allow it to pass through as a valid value. With Optionals, it becomes much simpler to cut through that nonsense. A null is a bug and you fix it (with the exception of json at the boundaries of your system, etc.) If you do find a value where you change your mind about its nullability, changing it to/from Optional will give you compile errors in exactly those other parts of the code that you now have to check/change.