suside
suside

Reputation: 695

How to enforce null safety annotation checks in kotlin?

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 \
 [email protected]:strict \
 [email protected]: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?

Upvotes: 5

Views: 437

Answers (1)

Klitos Kyriacou
Klitos Kyriacou

Reputation: 11621

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.

Upvotes: 6

Related Questions