forked from scala/scala3
-
Notifications
You must be signed in to change notification settings - Fork 2
scala with explicit nulls
Abel Nieto edited this page Mar 1, 2019
·
12 revisions
This is a version of the Dotty compiler where Scala reference types are non-nullable by default.
This means that val x: String = null
no longer type-checks. Instead, you can use union types to get nullability back: val x: String|Null = null
.
https://gist.github.com/abeln/9f79774bac111d99b3ae2cb9016a33e6
β = done | πΆ = in progress | π΄ = planned
- β
Null
is not a subtype of reference typesval x: String = null // no longer compiles
- β
Nullability is expressible via union types
val x: String|Null = null // ok
- β
Scala "nullifies" types that come from Java (argument types and method argument and return types)
val x = "abc".substring(2) // x has type String|JavaNull nullify(T) -> T|JavaNull (if T is not generic) nullify(C[T]) -> C[nullify(T)]|JavaNull (if T is generic)
- β
The
JavaNull
type is "transparent" w.r.t field selections:val x: Person = ??? // Person is defined in Java val y = x.getName() // inferred type is String|JavaNull y.length() // type-checks, because JavaNull is "transparent" // can also throw NPE
- β
Basic flow-sensitive type inference (missing: TASTy support https://github.com/abeln/dotty/issues/7#issuecomment-445057335)
Also propagated inside the condition
val x: String|Null = ??? if (x != null) { // x has type String here }
We also supportif (x != null && x.length > 0) {} // x.length types, even though x declared as String|Null
||
sif (x == null || x.length == 0) { } else { // x has type String here }
- πΆ Positive, negative, and run tests pass
- β Binary compatibility (details in https://github.com/abeln/dotty/issues/16)
- π΄ Java @NotNull annotation recognized
- π΄ Dotty bootstraps with explicit nulls
- π΄ PR to Dotty team
- TBD