by mdaniel · 1y ago · 0 comments
projects that do this drive me bananas
If I had the emotional energy, I'd open a JEP for a new @java.lang.NonNullReference and any type annotated with it would be a compiler error to assign null to it
public interface Alpha {}
@java.lang.NonNullReference
public interface Beta {}
Alpha a = null; // ok
Beta b = null; // compiler error
javac will tolerate this Beta b;
if (Random.randBoolean()) {
b = getBeta();
} else {
b = newBeta();
}
but I would need to squint at the language specification to see if dead code elimination is a nicety or a formality Beta b;
if (true) {
b = getBeta();
} else {
b = null; // I believe this will be elided and thus technically legal
}Java really suffers with optional because the language has such love for backwards compatibility that it's extremely unlikely that nulls would even be removed from the standard library in the first place. The fact that the ecosystem relies on ugly auto wiring hacks instead of mandating explicit constructors doesn't help either.
I still remember when Java 9 introduced modules. And I’m currently pulling my hair because Java 21 renamed all javax.* into jakarta.* because Javax was a trademark of Oracle, and all libs now require a “-jakartax” version for JDK 21.
But somehow I still have to deal with nulls everywhere and erased-at-runtime generics because Java loves backwards compatibility so much. The simple fact all libs released a “-jakartax” proves the entire ecosystem is fully maintained (plus CVEs means unmaintained libs aren’t allowed in production), so they could very well release a -jdk25 version with non-null types.
But like, when it comes to unwrappable optional/result thingies, there are libs in Python to mimic that kind of behavior from Rust and functional languages.
Anyway, I believe what you're referring to is the "?" syntax that annotates types in Kotlin but doesn't help the resulting bytecode, which means that every single library ever would need to convert to kotlin to benefit
fun doit() : java.io.InputStream? { return null }
kotlinc test.kt
javap -c test.class
public final java.io.InputStream doit();
Code:
0: aconst_null
1: areturn
So even they didn't have the courtesy of marking the result of a known Optional result as Optional<java.io.InputStream> when interfacing with the existing Java ecosystem