[Kotlin] Handle Java fields from Kotlin safely with Not Null (Non Null) / Nullable annotation [Java]

Apology and correction

At the time of this article's publication, I mentioned that the NonNull / Nullable annotations in ʻorg.springframework.lang` also worked, but this was incorrect. When these annotations were used, the completion notation on the IDE changed, but only a warning was issued at compile time.

We apologize for the correction.

Preface

By using annotations such as NotNull / Nullable in ʻorg.jetbrains.annotations, you can handle Java fields from KotlintoKotlin`.

See below for other annotations that can be used as well.

manner

All you have to do is give it as follows.

import org.jetbrains.annotations.NotNull;

public class Sample {
    private String field;

    @NotNull
    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }
}

What happens when you give it

Before granting, it is handled as String! Type (Platform type) on Kotlin as shown in the image below. スクリーンショット 2019-10-24 21.30.17.png

After granting, you can see that it is handled as a String type. スクリーンショット 2019-10-24 21.31.27.png

You can also treat it as a String? Type by changing the annotation to Nullable as shown below.

Change to Nullable


- import org.jetbrains.annotations.NotNull;
+ import org.jetbrains.annotations.Nullable;
- @NotNull
+ @Nullable
public String getField() {

スクリーンショット 2019-10-24 21.35.39.png

Supplement

When annotating a POJO-like object, it is better to add it to a getter. As you can see in the image, if you shake it in the field, you will be angry with "Initialize". スクリーンショット 2019-10-24 22.00.55.png

significance

When introducing Kotlin into a Java project or using the Java framework from Kotlin, it often behaves like "Initialize object with valueless constructor-> inject each value with setter". There may be cases.

In such a case, if you try to write the target object in Kotlin, you need to devise a lot, and you can say" Is it meaningful to write in Kotlin?". If you have an existing Java object and you need to rewrite it all one by one, the effort is not stupid. It's a good idea to create a utility that can be mapped to the Data class from the beginning, but it will cost more than rewriting.

If you want to do that, I think it's smarter to just annotate the getter (unless you want to make everything full Kotlin, of course, but the behavior you can achieve is the same. If so, I think it's okay to write it in Java separately).

Recommended Posts

[Kotlin] Handle Java fields from Kotlin safely with Not Null (Non Null) / Nullable annotation [Java]
Call a method with a Kotlin callback block from Java
[Java] Get Charset with Apathce Tika / Initialize String from Charset [Kotlin]
Android: How to deal with "Could not determine java version from '10 .0.1'"