首页 > 解决方案 > 我们可以使用 Kotlin 接口实现类似 Rust 的 Traits

问题描述

我们可以使用 Kotlin 接口实现 Rust 之类的 Traits 和通用 Traits 吗?

还有什么方法可以在 Kotlin 类/接口默认函数实现中使用类似 fn(&self) 的构造?

请问可以举一些例子吗?

谢谢

标签: kotlin

解决方案


我对 Rust 了解不多,我指的是这两个视频,你在说什么,通用特征自我解释。

如您所料,在 kotlin 中,您将使用接口和类来实现它们。

一个例子是:

interface GenericTrait { // Same as traits
    // <T:Any> just makes method to be called for non-null values, if you use <T>, you can pass null as well
    fun <T: Any> method(value: T)
}

class TraitImpl : GenericTrait { // Same as structs
    val isDisabled = Random.nextBoolean() // instance variable

    // you can access instance parameter using the this or even not using it at all as in below
    override fun <T: Any> method(value: T) {
        println("Type of value is ${value::class}, and the value is $value. I am $isDisabled")
        // or explicitly call ${this.isDisabled}, both are the same
    }
}

fun main() {
    TraitImpl().method("Hello")
    TraitImpl().method(23)

    TraitImpl().apply { // this: TraitImpl
        method(23)
        method(Unit)
    }
}

结果:

Type of value is class kotlin.String, and the value is Hello. I am true
Type of value is class kotlin.Int, and the value is 23. I am true
Type of value is class kotlin.Int, and the value is 23. I am false
Type of value is class kotlin.Unit, and the value is kotlin.Unit. I am false

如果您想像在 Rust 中那样将实现提取为扩展函数,则可以将其提取到外部。

interface GenericTrait {
    val isDisabled: Boolean
}

class TraitImpl : GenericTrait {
    override val isDisabled = Random.nextBoolean()
}

// define methods out of class declaration
fun <T: Any> GenericTrait.method(value: T) {
    println("Type of value is ${value::class}, and the value is $value. I am $isDisabled")
}

推荐阅读