繁体   English   中英

使用 Java 接口时的 Kotlin 接口实现行为

[英]Kotlin interface implementation behaviour when consuming Java interface

如果我在 Kotlin 中有一个接口:

interface KotlinInterface {
    val id: String
}

我可以像这样实现它:

class MyClass : KotlinInterface {
    override val id: String = "id"
}

但是,如果我要使用这样的 Java 接口:

public interface JavaInterface {
    String id = "id";
}

我不能以类似的方式覆盖id类变量:

class MyClass : JavaInterface {
    override val myId: String = JavaInterface.id //linter says: 'myId' overrides nothing
}

尽管id具有预定义值,但我也无法在其他地方使用它:

class MyClass : JavaInterface {
    val myArray: Array<String> = arrayOf(id) // linter would say that id is not defined rather than recognising it as the string “id”
}

看来我必须像这样使用它:

class MyClass {
    val id: String = JavaInterface.id
    val myArray: Array<String> = arrayOf(id)
}

谁能解释这种行为差异并指出我可能理解错误的任何内容?

在java接口中,每个变量都是静态final变量,静态变量不能被覆盖。 这就是为什么您会看到 lint 警告。

编辑1:

Kotlin 接口

  interface Ser {
       var name: String //abstract
    }

相当于java接口

public interface Ser {
   @NotNull
   String getName();

   void setName(@NotNull String var1);
}

我不能以类似的方式覆盖 id 类变量:

你也不能用 Java 来做; 相当于

class MyClass implements JavaInterface {
    @Override String getMyId() {
        return JavaInterface.id;
    }
}

getMyId不会覆盖任何内容。

如果你用 Java 编写

class MyClass implements JavaInterface {
    String id = JavaInterface.id;
}

你没有覆盖任何东西,因为你不能覆盖字段(此外, MyClass.id是一个非最终实例包私有字段,而JavaInterface.id是隐式最终静态公共字段,因为接口不允许任何其他种类)。

尽管 id 具有预定义值,但我也无法在其他地方使用它:

同样,与 Java 相同; 在 Java 和 Kotlin 中都需要JavaInterface.id ,或者import some.package.JavaInterface.id以仅使用id (在 Java 中import static )。

还有,如果一个差MyClass工具JavaInterface ,因为那时在Java中,你可以参考JavaInterface.id作为MyClass.idsomeInstanceOfMyClass.id ; 和里面MyClass就像id 但这通常被认为是错误的,所以 Kotlin 的设计者避免了它。

您在 Java 接口上声明了常量(public static String id = "id")。

而 Kotlin 接口声明了抽象属性。 请参阅 Kotlin 参考: https : //kotlinlang.org/docs/reference/interfaces.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM