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?
Android Dependency Injection using Dagger with Kotlin In Kotlin, the interface works exactly similar to Java 8, which means they can contain method implementation as well as abstract methods declaration. An interface can be implemented by a class in order to use its defined functionality.
Kotlin Data Class RequirementsData class can implement interfaces and extend to other classes. The parameters of the class can be either val or var type.
Android Dependency Injection using Dagger with Kotlin However, Kotlin uses object expressions to provide the same sub-class functionality. In Kotlin, we can create an object expression of an interface by implementing its abstract methods. This implementation technique is known as anonymous interface.
Multiple Interface Implementation – Since classes in Kotlin follow the concept of single inheritance, that is, each class can inherit only class, however, in case of interfaces a class supports multiple inheritance, also known as multiple conformance in Kotlin.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With