https://kotlinlang.org logo
#getting-started
Title
# getting-started
f

F0X

01/29/2021, 3:42 PM
If I have a base class with an extension property like this
open val SomeType.someProp: String
, how could I call the super implementation of this when overriding it in a subclass?
m

mkrussel

01/29/2021, 3:56 PM
You cannot override extensions. Instead you are shadowing the other value. But if that is what you are trying to do I'm guessing you just need to cast the
this
reference.
val SubType.someProp: String get() = (this as SomeType).someProp
.
j

jbnizet

01/29/2021, 3:56 PM
You can’t have an open extension property in the first place. And you can’t override extension properties, because they’re not polymorphic. They’re basically static utility methods.
☝️ 1
d

diesieben07

01/29/2021, 4:03 PM
You very much can have an extension property in a class - it will be both a member and an extension. And you can very much override them. But there is no syntax for calling the super implementation in this case. You have to work around it like this:
Copy code
open class Base  {
    val SomeType.someProp: String = getSomeProp(this@someProp)
    protected open fun getSomeProp(receiver: SomeType): String = TODO()
}

class Ext : Base {
    override fun getSomeProp(receiver: SomeType): String = super.getSomeProp(receiver) + "extension"
}
m

mkrussel

01/29/2021, 4:06 PM
That makes more sense. I've not tried to creating an open extension like that. So I don't know if it is possible to call super.
Kotlin docs don't mention anything about it.
d

diesieben07

01/29/2021, 4:08 PM
Yeah, its very much a niche feature I think
r

Ruckus

01/29/2021, 4:26 PM
This is a use case that will likely be resolved if/when Kotlin adds support for multiple receivers
j

jbnizet

01/29/2021, 4:46 PM
Ah, I misunderstood the question, sorry.
f

F0X

01/29/2021, 6:57 PM
Sorry for the misleading question, @diesieben07 had the right answer, ty
2 Views