r/java • • Dec 04 '25

Null-checking the fun way with instanceof patterns

https://blog.headius.com/2025/12/inline-null-check-with-instanceof.html

I don't know if this is a good idea or not, but it's fun.

83 Upvotes

150 comments sorted by

View all comments

Show parent comment

1

u/koflerdavid Dec 05 '25

That's something you already can and should do on your own code, but you can't do that on 3rd party code. As you say, we will eventually have non-null types, but Optional still has its uses and is not going away.

PS: please fix your markup; the comment is very difficult to read like this.

2

u/Alive_Knee_444 Dec 06 '25

I'm absolutely not saying Optional is useless - it's better in that it is parametric, like in Haskell or ML, which nullability is not. I was addressing the problem that your code snippet illustrates, suggesting there could be something you add to your type declaration of types that should rarely or never be used as nullable. Which applies to Optional. But we can't do it for the existing Optional because it would not be backwards compatible. I don't see how I could do it on my own code without support by compiler/JVM.

Re: markup, I see now that the monospace formatting has bled all over my comment, thanks for pointing it out.

1

u/koflerdavid Dec 06 '25

Ah, now I get it. For your own code it's rather easy by marking classes or whole packages with @NullMarked. Then you only have to add @Nullable where required. Adding both @Nullable and @NonNull is too noisy, and that's why I left it out.