3 ms·
Using my suggestion, the signature would simply be "T findAny();" - while "T!" would represent non-nullable T. So the opposite of the Kotlin/Typescript/etc. wa
by derriz 2y ago
Using my suggestion, the signature would simply be "T findAny();" - while "T!" would represent non-nullable T. So the opposite of the Kotlin/Typescript/etc. way where the default is not-nullable and you'd have something like "T? findAny();".
It would be a language level change and would require language level syntax extensions to provide mappings between T and T!.
Like how we're used to having to add "final" to most variable declarations, you'd add "!" to a class type indicate not-null. Contra-variance would allow you to add ! to return values without breaking interface compatibility so you could migrate your code base in steps. Actually to be honest I'm just throwing this idea out there, I haven't given it deep thought.
Without language level support, Optional is a broken design. You've just multiplied the state space: the Optional instance can be null, the Optional instance can be not-null but empty, the Optional instance can be not-null and non-empty but the content is null and finally the Optional instance can be not-null and non-empty and the contained value can be non-null. Java's type system doesn't distinguish.
- ivan_gammel 2y ago>Actually to be honest I'm just throwing this idea out there, I haven't given it deep thought. I think the problem is much more complex if done properly, Java way, with full consideration. E.g. Optional has fluent interface which often becomes useful to avoid lots of nested if’s. To emulate chaining with nullable values you do need ‘?’ syntax. >the Optional instance can be null When return type is Optional, it is an error in 100% cases to return null, so it’s a valid case for NPE. A vary rare problem. > the Optional instance can be not-null and non-empty but the content is null Optional of null content is empty by design. Did you mean something else?
- derriz 2y agoNo doubt the problem is more complex and like I said would need language level syntax support. Sorry yes you're correct, optional containing null is the same as an empty optional. So there are 3 cases, not 4. But saying that "it's a valid case for NPE" missed the point I believe as you're taking about dealing with the issue at runtime. The killer feature of having language level support for distinguishing null and not-null is that these errors are flagged at compile time, not runtime.
- ivan_gammel 2y ago>But saying that "it's a valid case for NPE" missed the point I believe as you're taking about dealing with the issue at runtime. What I mean is that this issue (null instead of Optional) is rare enough not to bother about it and let NPE happen. Language support for null/non-null values in general would be nice, of course.