Kotlin - how to return "self type" in a subclass? (without an extension function)
Asked Answered
B

0

7

Let's have these classes:

class A {
    fun foo(): A = this
}

class B: A() {
    fun bar() { ... }
}

Now I would like Kotlin to detect when I call foo on B, and give me the result typed as B. So that I can write:

B().foo().bar()

With kotlin 1.4.20, this is not possible - it would need an explicit cast to B after foo().

Perhaps it could be handled by the compiler, if it clearly sees that the function returns this. Or maybe we could hint it explicitly...

class A {
    fun <Self> foo(): Self = this
}

I can't use extension function because I need the Java classes to have the properties.

I have read this Kotlin forum thread on that topic, however I didn't see this case being solved. But maybe it's implied. Either way, it's not implemented at the moment.

One more nice article here.

I have read this SO question How to specify "own type" as return type in Kotlin and I have tried the "recursive type" approach, but it doesn't work if I want to have the type on the subclasses as well as base class:

Type parameter Me of 'HasStatus' has inconsistent values: BaseClass, Subclass

Is there any other trick to persuade Kotlin to return the type of this if a method returns this?

Beaming answered 17/12, 2020 at 0:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.