Skip to content

scala with explicit nulls

Abel Nieto edited this page Mar 1, 2019 · 12 revisions

project logo

Scala with Explicit Nulls

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.

Design Doc

https://gist.github.com/abeln/9f79774bac111d99b3ae2cb9016a33e6

Features

βœ… = done | πŸ”Ά = in progress | πŸ”΄ = planned

πŸ”Ά Initial version

  • βœ… Null is not a subtype of reference types
    val 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)
    val x: String|Null = ???
    if (x != null) {
      // x has type String here
    }
    
    Also propagated inside the condition
    if (x != null && x.length > 0) {} // x.length types, even though x declared as String|Null
    
    We also support ||s
    if (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

πŸ”΄ Feature complete

  • TBD