subclass

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

拜拜、爱过 提交于 2021-01-01 04:18:22
问题 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