Aaron Digulla
Aaron Digulla

Reputation: 328614

How can I tell the Kotlin compiler that a Java method will never return null?

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

Upvotes: 0

Views: 173

Answers (3)

Aaron Digulla
Aaron Digulla

Reputation: 328614

You can use extension functions for this. If you have a method String foo() in the class Test, you can define the extension function

fun Test.safeFoo(): String = this.foo()!!

The advantage is that the code is pretty obious.

The disadvantage of this approach is that you need to write a lot of boiler plate code. You also have to define the extension function in a place where all your modules or projects can see it. Also, writing that much code just to avoid !! feels like overkill.

It should also be possible to write a Kotlin compiler extension which generates them for you but the extension would need to know which methods never return null.

Upvotes: 0

Tenfour04
Tenfour04

Reputation: 93629

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.

Upvotes: 1

user2340612
user2340612

Reputation: 10713

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.

Upvotes: 2

Related Questions