Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin overriding supertype variables

Tags:

kotlin

Consider two classes:

abstract class ParentRepository {}

class ChildRepository : ParentRepository {}

abstract class ParentClass {
    protected abstract var repository: ParentRepository
}

class ChildClass : ParentClass {
    override var repository: ChildRepository
}

The last part won't work:

override var repository: ChildRepository

It will complain:

Type of 'repository' doesn't match the type of the overridden var-property 'protected abstract var repository: ParentRepository

I understand the problem, but I don't see the reason why this shouldn't work – ChildRepository is an instance of ParentRepository and this is a common thing I am used to from Java.

like image 539
Vojtěch Avatar asked Feb 23 '18 11:02

Vojtěch


People also ask

Can we override variables in Kotlin?

In Java, every method is virtual by default; therefore, each method can be overridden by any derived class. In Kotlin, you would have to tag the function as being opened to redefine it.

How do you override property in Kotlin?

To override a property of the base class in the derived class, we use the override keyword.

How do you override fun in Kotlin?

To override a method of the base class in the derived class, we use the override keyword followed by the fun keyword and the method name to be overridden.

Is multiple inheritance possible in Kotlin?

Before we proceed, I must note that because classes can have state and initialization logic (including side-effects), Kotlin does not allow true multiple inheritance as that could cause havoc in slightly more complex class hierarchies (it does allow declaring properties and implementing methods in interfaces, though, ...


1 Answers

You have to declare repository as val. You can still override it as var:

protected abstract val repository: ParentRepository

override var repository: ChildRepository
like image 135
dipdipdip Avatar answered Oct 21 '22 17:10

dipdipdip