How to enforce null safety annotation checks in kotlin?

Viewed 121

Consider this example:

import java.math.BigDecimal

fun main(args: Array<String>) {
  val s: String? = null
  BigDecimal(s)
}

it compiles without any warnings (with cli kotlinc and IntelliJ) and throws at runtime:

Exception in thread "main" java.lang.NullPointerException
    at java.math.BigDecimal.<init>(BigDecimal.java:809)
    ...

I tried to build it in different ways according to docs like so:

kotlinc \
 -Xnullability-annotations=@javax.annotation:strict \
 -Xnullability-annotations=@org.jetbrains.annotations:strict \
 -Xjsr305=strict \
Main.kt -d main.jar

Annotation seems to be there (as seen in IntelliJ):

@NotNull annotation in BigDecimal constructor

Docs clearly states that:

Java types that have nullability annotations are represented not as platform types, but as actual nullable or non-null Kotlin types.

What am I missing here?

1 Answers

The argument to the BigDecimal constructor is treated as a platform type because the constructor is not actually annotated.

The @NotNull annotation is calculated on-the-fly by the IDE by examining the source code. If you ctrl+click on the constructor, you will go to the source code where you will see there is no annotation.

Related