实现Java接口的Kotlin数据类 [英] Kotlin data class implementing Java interface
问题描述
我正在尝试将Kotlin引入我当前的项目中。我决定从实体开始,实体似乎可以完美地映射到数据类。
例如,我有一个数据类:
I'm trying to introduce Kotlin into my current project. 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
它实现了Java接口:
Which implements Java interface:
public interface Entity {
Long getId();
}
但是由于某些原因,编译器无法理解该方法是否已经实现:
But for some reason compiler doesn't understand that method is implemented already:
类 Video必须声明为抽象或实现抽象成员public abstract fun getId():kotlin.Long!定义在net.alfad.data.Entity
Class 'Video' must be declared abstract or implement abstract member public abstract fun getId(): kotlin.Long! defined in net.alfad.data.Entity
是否必须对id参数使用其他关键字?什么是!
Do I have to use any additional keywords for id param? What does "!" mean in the signature?
推荐答案
这里的问题是Kotlin加载Java类 Entity
首先,它将 getId
视为函数,而不是某些属性的获取器。 Kotlin类中的属性获取器无法覆盖函数,因此属性 id
不绑定为 getId
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. 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类中覆盖原始函数 getId
。这样做会导致新函数与字节码中 id
的getter之间的JVM签名冲突,因此,还应通过使属性 private
:
To workaround this, you should override the original function getId
in your Kotlin class. 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
:
data class Video(
private val id: Long,
...
) {
override fun getId() = id
...
}
请注意,此答案已从此处改编: https://stackoverflow.com/a/32971284/288456
Note that this answer has been adapted from here: https://stackoverflow.com/a/32971284/288456
这篇关于实现Java接口的Kotlin数据类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!