Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Issue implementing interface with getters

Tags:

kotlin

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?

like image 851
dev Avatar asked Jun 14 '18 21:06

dev


People also ask

CAN interface have getters and setters?

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.

CAN interface have method implementation Kotlin?

In Kotlin, the interface works exactly similar to Java 8, which means they can contain method implementation as well as abstract methods declaration.

Can a Kotlin class implement a Java interface?

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.

How do you extend a class and implement an interface in Kotlin?

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.


2 Answers

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
like image 70
Pawel Avatar answered Nov 15 '22 10:11

Pawel


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.

like image 36
Alexey Romanov Avatar answered Nov 15 '22 11:11

Alexey Romanov