This is more of an interop question than refactori...
# java-to-kotlin-refactoring
w
This is more of an interop question than refactoring, but I couldn't find a more appropriate channel: I'm working on a Kotlin class which implements a Java interface. One of the methods in the Java interface has parameters annotated with
@Nonnull
. Kotlin knows that my implementing function should have non-null types for those parameters. The only problem is, the Java code which calls the interface passes
null
for these
@Nonnull
annotated parameters. Kotlin, of course, throws an exception when
null
is passed to a non-null type. I'd like to change the signature of my function to have nullable types, but then Kotlin tells me that its no longer implementing the function it should be. Is there any way to tell Kotlin to ignore the annotations on that method or the specific parameters? I've filed a bug report with the maintainer of the interface, but I'd like to move forward before the fix is released.
I've tried specifying annotations for that function in an
annotations.xml
file, but it doesn't seem to override the annotations in code.
k
Would it be possible to extend the problematic interface with one without the annotation in Java?
Copy code
// BadInterface.java
interface BadInterface {
    void foo(@Nonnull String bar);
}

// GoodInterface.java
interface GoodInterface extends BadInterface {
    @Override
    void foo(@Nullable String bar);  // Java compiler ok with this, ignore IDE warnings
}

// Kotlin code
class MyObj : GoodInterface {
    fun foo(bar: String?) {...}
}

val myObj: BadInterface = MyObj()
myObj.foo(null)
w
I like that idea. I was thinking about changing my implementation of that specific class to Java, or adding a shim implemented in Java calling my Kotlin class, but I think adding the interface would work and is probably easier and clearer.
k
if one can change java code why not remove annotation?:)
k
Because the original interface is in a third party library. Having said that, I suppose a possibly preferable option might be to locally fork the third-party library and fix it yourself until the original library gets fixed. (Obviously only an option if that third-party library supplies its source code.)
w
In my case, it's an application managed by a different team. I've filed a bug report and I'm sure they'll get to it in the next release, but I'm hoping to get my work done before (or at least independent of) their next release. As Klitos suggested, I've added a Java interface to my otherwise Kotlin project which changes the nullability annotation on the problematic method/parameters.