简体   繁体   English

实现 Java 接口的 Kotlin 数据类

[英]Kotlin data class implementing Java interface

I'm trying to introduce Kotlin into my current project.我正在尝试将 Kotlin 引入我当前的项目。 I've decided to begin with entities, which seem to map perfectly to data classes.我决定从实体开始,它们似乎完美地映射到数据类。 For example I have a data class:例如我有一个数据类:

data class Video(val id: Long, val ownerId: Long, val title: String, val description: String? = null,
             val imgLink: String? = null, val created: Date? = null, val accessKey: String? = null,
             val views: Long? = null, val comments: Long? = null, val videoLink: String? = null): Entity

Which implements Java interface:其中实现Java接口:

public interface Entity {
   Long getId();  
}

But for some reason compiler doesn't understand that method is implemented already:但由于某种原因,编译器不明白该方法已经实现:

Class 'Video' must be declared abstract or implement abstract member public abstract fun getId(): kotlin.Long!类“视频”必须声明为抽象或实现抽象成员 public abstract fun getId(): kotlin.Long! defined in net.alfad.data.Entity在 net.alfad.data.Entity 中定义

Do I have to use any additional keywords for id param?我是否必须为 id 参数使用任何其他关键字? What does "!" “!”是什么意思mean in the signature?在签名中是什么意思?

The problem here is that Kotlin loads the Java class Entity first and it sees getId as a function, not as a getter of some property.这里的问题是 Kotlin 首先加载 Java 类Entity并将getId视为一个函数,而不是某个属性的 getter。 A property getter in a Kotlin class cannot override a function, so the property id is not bound as an implementation of the getId function. Kotlin 类中的属性 getter 不能覆盖函数,因此属性id未绑定为getId函数的实现。

To workaround this, you should override the original function getId in your Kotlin class.要解决此问题,您应该覆盖 Kotlin 类中的原始函数getId Doing so will result in JVM signature clash between your new function and id 's getter in the bytecode, so you should also prevent the compiler from generating the getter by making the property private :这样做会导致新函数和字节码中id的 getter 之间的 JVM 签名冲突,因此您还应该通过将属性private防止编译器生成 getter:

data class Video(
    private val id: Long,
    ...
): Entity {
    override fun getId() = id

    ...
}

Note that this answer has been adapted from here: https://stackoverflow.com/a/32971284/288456请注意,此答案已从此处改编: https : //stackoverflow.com/a/32971284/288456

If this is your whole data class then you're not overriding getId().如果这是您的整个数据类,那么您不会覆盖 getId()。 I see that you have a property called id and Kotlin should generate a getter for that but that won't be marked with the override keyword which you need to indicate that you're overriding an abstract function.我看到您有一个名为 id 的属性,Kotlin 应该为此生成一个 getter,但不会用 override 关键字标记,您需要指示您正在覆盖抽象函数。

-- EDIT -- Alexander beat me to it! - 编辑 - 亚历山大击败了我! His answer is better anyway!反正他的回答更好! ;) ;)

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

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