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.
By using annotations such as NotNull
/ Nullable
in ʻorg.jetbrains.annotations, you can handle
Java fields from
Kotlinto
Kotlin`.
See below for other annotations that can be used as well.
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;
}
}
Before granting, it is handled as String!
Type (Platform type) on Kotlin
as shown in the image below.
After granting, you can see that it is handled as a String
type.
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() {
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".
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).