如何指定“自己的类型"?作为Kotlin的返回类型 [英] How to specify "own type" as return type in Kotlin
本文介绍了如何指定“自己的类型"?作为Kotlin的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将函数的返回类型指定为被调用对象的类型?
Is there a way to specify the return type of a function to be the type of the called object?
例如
trait Foo {
fun bar(): <??> /* what to put here? */ {
return this
}
}
class FooClassA : Foo {
fun a() {}
}
class FooClassB : Foo {
fun b() {}
}
// this is the desired effect:
val a = FooClassA().bar() // should be of type FooClassA
a.a() // so this would work
val b = FooClassB().bar() // should be of type FooClassB
b.b() // so this would work
实际上,这大致相当于Objective-C中的instancetype
或Swift中的Self
.
In effect, this would be roughly equivalent to instancetype
in Objective-C or Self
in Swift.
推荐答案
没有语言功能支持此功能,但是您始终可以使用递归泛型(许多库使用的模式):
There's no language feature supporting this, but you can always use recursive generics (which is the pattern many libraries use):
// Define a recursive generic parameter Me
trait Foo<Me: Foo<Me>> {
fun bar(): Me {
// Here we have to cast, because the compiler does not know that Me is the same as this class
return this as Me
}
}
// In subclasses, pass itself to the superclass as an argument:
class FooClassA : Foo<FooClassA> {
fun a() {}
}
class FooClassB : Foo<FooClassB> {
fun b() {}
}
这篇关于如何指定“自己的类型"?作为Kotlin的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文