I am trying to implement an interface with getter method which matches the constructor parameter name of the implementing class.
interface Car{
fun getModel(): Int
}
class Honda(val model: Int): Car {
override fun getModel(): Int {
}
}
If Honda
doesn't implement getModel()
, we get an Accidental Override
error. If Honda
implements getModel()
, we get a Platform declaration clash
error.
I can change the name of the parameter in the Honda
constructor, which fixes the problem, but it feels like a redundant getter method.
interface Car{
fun getModel(): Int
}
class Honda(val modelParam: Int): Car {
override fun getModel() = modelParam
}
Is there a better way to implement such interfaces?
You cannot define instance fields in interfaces (unless they are constant - static final - values, thanks to Jon), since they're part of the implementation only. Thus, only the getter and setter are in the interface, whereas the field comes up in the implementation.
In Kotlin, the interface works exactly similar to Java 8, which means they can contain method implementation as well as abstract methods declaration.
Kotlin allows Interface to have code which means a class can implement an Interface, and inherit the behavior from it. After using Kotlin in Android development for a while, I've just realized the benefit of Interface in Kotlin. In Java 6, Interface can only be used to describe the behaviors, but not implement them.
Extending a Class and Implementing Two Interfaces First, like Java, a Kotlin class can only inherit one superclass, but it can implement multiple interfaces. Kotlin uses the colon character “:” to indicate both inheritance and interfaces' implementation.
You can declare properties in interface:
interface Car{
val model : Int
}
Then in implementation / constructor you need to add override
keyword.
class Honda(override val model : Int): Car
For case where the accepted answer isn't applicable because you can't change the interface, or the interface is a Java one,
class Honda(private val model: Int): Car {
override fun getModel(): Int = model
}
For a Java interface, it can still be accessed as .model
in Kotlin.
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