logoalt Hacker News

inigyoutoday at 12:16 PM3 repliesview on HN

How would a non-nullable class field work in Java when it can be initiqlized by arbitrary imperative code that can read it while it's being initialized?


Replies

tsimionescutoday at 1:42 PM

Look at how Go did it. Any value type has a defined 0 value, and any variable of field of that type is initialized to 0 by default. So any un-initialized non-null able value type field could have the corresponding 0 value.

show 1 reply
wiseowisetoday at 1:36 PM

How can Kotlin do it?

show 2 replies
jmyeettoday at 12:27 PM

The type erasure version of this would look a lot like Hack [1]. So generic arguments would simply have a ? if they allow nulls eg List<?Point>. The list itself couldn't be null unless it was ?List<?Point>.

Now, one can argue that this is just smoke and mirrors with type erasure and it is but you can already put a Date into a List<Point> if you're so inclined because the JVM doesn't know the difference, hence type erasure. So this is no different.

I'm no JVM expert but from reading the article it seems like the chosen solution for value classes is to treat them all as a single L-type in the JVM where each primitive type is its own L-type. If I read the correctly, it means that if you have a Point value class then on the JVM level you'll be able to stuff any value class into there if you're so incline, just like with List<Point>.

Obviously we need to be concerned with fuzzing (moreso in C++) but here really we're just trying to have sensible defaults that aren't guaranteed because we can't design the language how we want from the ground up without making a new language.

Oh and there is a prosopal for this [2]. Personally, I prefer the Hack version.

[1]: https://docs.hhvm.com/hack/types/nullable-types/

[2]: https://openjdk.org/jeps/8303099

show 1 reply