Home > Back-end >  How can I tell the Kotlin compiler that a Java method will never return null?
How can I tell the Kotlin compiler that a Java method will never return null?

Time:11-02

I don't or can't modify the Java source coe. The goal to configure just the Kotlin compiler to know what is nullable and what isn't.

CodePudding user response:

You can specify the type manually if you know something will never be null. For example, if you have the following Java code:

public static Foo test() {
    return null;
}

and you call it in Kotlin like this:

val result = Foo.test()

then result will have a type of Foo! by default – which means it can be either Foo or Foo?.. the compiler doesn't have enough information to determine that.

However, you can force the type manually:

val result: Foo = Foo.test()
// use "result" as a non-nullable type

Of course, if at runtime that is not true, you'll get a NullPointerException.

For reference, please check the documentation.

CodePudding user response:

If you really can't add the annotations to the Java methods/values from Java, then you can use the elvis operator ?: with a throw:

val a: Int? = null
val b: Int = a as? Int ?: throw NullPointerException("a was null")
println(b   5)

// Exception in thread "main" java.lang.NullPointerException: a was null

If a did turn out to be null, you'd get an NPE. Or throw some other exception.

b remains correctly a non-nullable Int.

val a: Int? = 10
val b: Int = a as? Int ?: throw NullPointerException("a was null")
println(b   5)

// 15

For some other Java method:

val b: Int = valueFromJava() as? Int ?: throw NullPointerException("a was null")
println(b   5)

CodePudding user response:

I don't know of a way to configure the compiler for this, but IntelliJ IDEA has a feature that allows you to add annotations to code via an XML file called external annotations.

You can add the Jetbrains @Nullable and @NotNull annotations to library code, but when I've tried it, it only results in compiler warnings rather than errors when you use incorrect nullability in your code. These same annotations generate compiler errors when used directly in the source code. I don't know why there is a difference in behavior.

  • Related