相关疑难解决方法(0)

如何在Kotlin中指定"自己的类型"作为返回类型

有没有办法将函数的返回类型指定为被调用对象的类型?

例如

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
Run Code Online (Sandbox Code Playgroud)

实际上,这与instancetypeObjective-C或SelfSwift中的大致相同.

kotlin

13
推荐指数
4
解决办法
3386
查看次数

标签 统计

kotlin ×1