How can I override the java method and change the nullability of the parameter?

I am redefining a method from the Java library, and the parameter for the function is annotated as @NonNull . However, when a method is called, the parameter often comes with a null value. When I override the method in Kotlin, it makes me respect the @NonNull annotation and mark the parameter as invalid. Of course, Kotlin throws a runtime exception when a parameter comes up with a null value. Is there a way to override the method in Kotlin and ignore the @NonNull annotation?

In particular, I use the appcompat library for Android. This method is in AppCompatActivity.java

 @CallSuper public void onSupportActionModeFinished(@NonNull ActionMode mode) { } 

Overriding in Kotlin:

 override fun onSupportActionModeFinished(mode: ActionMode) { super.onSupportActionModeFinished(mode) } 
+5
source share
1 answer

There seems to be no easy way to suppress annotation processing with NULL by the Kotlin compiler.

As a workaround, you can create an intermediate derived class with @Nullable annotation in Java: when the Kotlin compiler sees both @Nullable and @NonNull on the same code element, it behaves as if annotations with null values ​​are missing. Then just subclass it in Kotlin. Example:

Consider a class with the @NonNull parameter in Java:

 abstract class Base { public abstract void f(@NonNull String str); //... } 

Kotlin understands the annotation: f(str: String) , the type is not null.

Now we extend Base in Java, redefine the method and add the @Nullable annotation to the parameter in Intermediate :

 abstract class Intermediate extends Base { @Override public abstract void f(@Nullable String str); } 

For Intermediate , Kotlin sees f(str: String!) , The parameter is of the platform type , i.e. its uncertainty is unknown.

After that, you can declare the NULL parameter in a subclass of Kotlin Intermediate :

 class Derived(): Intermediate() { override fun f(url: String?) { ... } } 
+4
source

Source: https://habr.com/ru/post/1246186/


All Articles