How to implement this Java interface in Kotlin?

ice1000 picture ice1000 · May 23, 2017 · Viewed 41.8k times · Source

Since Kotlin doesn't have primitives, how could this interface be implemented?

public interface A {
  @NotNull Object get(@NotNull Integer i);
  @NotNull Object get(int i);
}

I cannot change the Java code since it's a compiled class file in a binary library.

Answer

hotkey picture hotkey · May 23, 2017

If a single implementation, as in @zsmb13's answer, is not enough for you and you need separate implementations for the two methods in Kotlin, then you can add an intermediate interface overriding the method accepting Integer with a nullable parameter:

private interface IntermediateA : A {
    override fun get(i: Int?): Any
}

Implementing this interface instead of the original A, the Kotlin compiler will distinguish the two methods, allowing you to override them as follows:

class C : IntermediateA {
    override fun get(i: Int) = "primitive"
    override fun get(i: Int?) = "boxed"
}

val a: A = C()
println(a.get(1)) // primitive
println(a.get(1 as Int?)) // boxed

If you had access to the Java code, you could fix this by adding a nullability annotation to the method accepting the boxed type:

Object get(@Nullable Integer i);

The Kotlin compiler understands different kinds of nullability annotations, here's the list.