Kotlin data class implementing Java interface

前端 未结 2 1372
猫巷女王i
猫巷女王i 2020-12-17 08:16

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

2条回答
  •  被撕碎了的回忆
    2020-12-17 08:34

    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

提交回复
热议问题