Skip to content
Alessandro Autiero
Go back

Backwards compatible, null safe, non-null by default type system proposal

Introduction

A major challenge in keeping java up to date going forward is probably keeping the type system competitive with other programming languages. Java’s type system is definitely moving forwards thanks to project Valhalla’s unified type system, value types and primitive classes, but, as far as I know, there is no clear direction on how to address null safety as of today. This is what I’d like to discuss here. I’d also like to propose something to OpenJDK mailing lists in the future.

Optional

In Java 8, the Optional class was introduced to provide a wrapper for non-null values and to complement the functional programming style introduced with Streams. The goal with this utility class wasn’t though to introduce a general-purpose null safe type like Swift’s Optional, Rust’s Option or Haskell’s Maybe. Other articles have already shown that Java’s Optional is also quite slow when compared to other languages’ alternatives, but this is to be expected considering that it’s only a wrapper class. Thanks to project Valhalla’s value types, though, Optional could become a primitive value-based class, mitigating these performance issues. Once that is done, it could be used as an opportunity to expand Java’s type system.

Can Kotlin help us?

When designing a type-safe system, the first thought might be to look at what Kotlin is doing considering its reputation as a type-safe and more expressive alternative to Java in the JVM(and also outside, but that’s out of the scope of this discussion). Types are non-null by default in Kotlin, while nullable types can be declared by adding a question mark after the type’s name(platform types are also out of the scope of this article). Nullable and non-null types, though, are treated by the compiler as completely different types: this is not an approach that is suitable for Java as backwards compatibility has always been a priority. This approach would also make Optional practically an anti-pattern, so let’s move on.

Learning from Swift

Instead, let’s look at Swift. As in Kotlin, types are non-null by default and can be declared as nullable by appending a question mark to the type’s name, though, unlike Kotlin, Swift considers nullable values as instances of Optional, not as completely different types. This means that the question mark is simply syntactic sugar for declaring said type as wrapped by Optional and its value as Optional.none if nil is assigned to it, or as Optional.some(value). To better understand this concept consider the following equivalent pairs of local variable declarations:

let nullableWithValue: Int? = 10
let nullableWithValue: Optional<Int> = Optional.some(10)

let nullableWithNoValue: Int? = nil
let nullableWithNoValue: Int? = Optional.none

let nullableWithOptionalValue: Int?? = 10
let nullableWithOptionalValue: Optional<Optional<Int>>> = Optional.some(Optional.some(10))

The approach taken by Swift is exacly what we need for Java. This is because we already have this concept in Java for primitive wrappers, it’s called boxing.

Optional and Boxing in Java

Just like the Java compiler applies boxing at compile time for primitive wrappers, the same could be done for Optional. This table shows an example of how values could be autoboxed based on their type:

Standard Type Optional Type
non-null literal and class initializations Optional.of(literal)
null literal Optional.empty()
method invocation with nullable return type Optional.ofNullable(methodInvocation())
method invocation with non-null return type Optional.of(methodInvocation())

The previous examples shown is Swift would look like this in Java(assuming project valhalla is already shipped):

int? nullableWithValue = 10;
Optional<int> nullableWithValue = Optional.of(10);

int? nullableWithNoValue = null;
int? nullableWithNoValue = Optional.empty();

int?? nullableWithOptionalValue = 10;
Optional<Optional<int>> nullableWithOptionalValue = Optional.of(Optional.of(10));

This would allow java to leverage the already existing Optional class, provide functional style method for nullable types and make null safety the job of the compiler.

Learning from Dart

Dart is a programming language developed by Google originally to overthrow Javascript. While it has certainly miserably failed at that, it’s been used more recently to develop Flutter, a cross-platform framework that targets mobile, desktop and web platforms. One year ago, they introduced a null safe type system similar to Kotlin’s in a new release of Dart. Considering that massive amounts of code had been already written using previous versions of Dart, Google’s engineers decided to introduce the concept of “sound null safety” to the language to allow itself to transition from a nullable by default to a non-null by default type system without breaking backwards compatibility. In short, null safe code can be mixed with non-null safe code coming from a library that hasn’t migrated yet to the new type system, but assigning a potentially nullable type to a non-null type will result in an exception being thrown. If you are interested in a more detailed explanation click here. This exact approach could be used in Java to introduce null safety as a default instead of as an opt-in feature.

Companion operators

All languages mentioned previously also provide operators, such as the Elvis operator and bang operator to work easily with nullable types. Considering that Optional already provides these methods as object-oriented alternatives, those operators could be mapped to the latter in this way:

Operator Optional Method
Elvis operator with a literal Optional#orElse
Elvis operator with lazy value Optional#orElseGet
Null safe call to non-null type Optional#map
Null safe call to nullable type Optional#flatMap
Null safe call to void method call Optional#ifPresent
Cascade notation Optional#peek (Proposal, from Stream#peek)
Bang operator Optional#orElseThrow

The cascade notation is also inspired by Dart and could be very useful in Java both for nullable and non-null types. If you have never used Dart, you can read about it here.

Conclusion

I’d like to know what others think about this approach and, if any maintainer reads this, if it’s technically feasible. I’ve already worked with the compiler in the past quite a lot, so I would be very happy to help this be a reality. Thanks for your time!


Originally posted on r/java on March 20, 2022.

A revised version of this proposal was later sent to the OpenJDK amber-dev mailing list on May 15, 2022: “PROPOSAL: Null safe type system”.



Previous Post
Named and Optional Parameters in Java
Next Post
Named and Optional Parameters in Java 17 - Redefined Version