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接口:

public interface Entity {
   Long getId();  
}

但是出于某种原因,编译器不理解该方法已经实现:

Class 'Video' must be declared abstract or implement abstract member public abstract fun getId(): kotlin.Long! defined in net.alfad.data.Entity

Do I have to use any additional keywords for id param? What does "!" mean in the signature?

推荐答案

这里的问题是,Kotlin首先加载Java类Entity,并将getId视为一个函数,而不是某个属性的getter.Kotlin类中的属性getter无法重写函数,因此属性id未绑定为getId函数的实现.

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,
    ...
): Entity {
    override fun getId() = id

    ...
}

注意,这个答案是从这里改编的:https://stackoverflow.com/a/32971284/288456

Kotlin相关问答推荐

在Kotlin中,有没有一种函数方法将一个列表(N个元素)映射到一个相邻元素之和列表(N—1个元素)?

使用数据存储首选项Kotlin Jetpack Compose

&x是T&q;和&q;(x为?T)!=空(&Q;)?

协程子作业(job)取消

是什么让 Kotlin 中的 String 类能够使用方括号?

关于 Kotlin 函数类型转换的问题

如何从kotlin中的ArrayList中删除所有元素

Kotlin - 创建指定长度的随机整数的 ArrayList?

如何在主线程上使用 Kotlin 协程 await()

无法在 kotlin android 中以编程方式禁用 EditText

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

为什么 Kotlin Pair 中的条目不可变?

如何使用kotlin中的反射查找包中的所有类

在Kotlin中传递并使用函数作为构造函数参数

Kotlin使用运行时断言进行空判断?

如何将 Kotlin 日期中的字符串或时间戳格式化为指定的首选格式?

Kotlin数据类打包

将字符串编码为Kotlin中的UTF-8

如何在 IntelliJ IDEA 中禁用粘贴时将 Java 转换为 Kotlin?

Kotlin for assertThat(foo, instanceOf(Bar.class))