Search code examples
javaoverridingkotlindata-class

Kotlin data class implementing Java interface


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?


Solution

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

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