Kotlin data class implementing Java interface

别说谁变了你拦得住时间么 提交于 2020-06-10 07:22:28

问题


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

Which implements Java interface:

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! defined in net.alfad.data.Entity

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


回答1:


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.

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

    ...
}

Note that this answer has been adapted from here: https://stackoverflow.com/a/32971284/288456




回答2:


If this is your whole data class then you're not overriding 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.

-- EDIT -- Alexander beat me to it! His answer is better anyway! ;)



来源:https://stackoverflow.com/questions/35631290/kotlin-data-class-implementing-java-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!