Kotlin - how to return “self type” in a subclass? (without an extension function)

☆樱花仙子☆ 提交于 2021-01-01 04:19:15

问题


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 a 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?

来源:https://stackoverflow.com/questions/65333206/kotlin-how-to-return-self-type-in-a-subclass-without-an-extension-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!