kotlin - 我们可以使用 Kotlin 接口实现类似 Rust 的 Traits
问题描述
我们可以使用 Kotlin 接口实现 Rust 之类的 Traits 和通用 Traits 吗?
还有什么方法可以在 Kotlin 类/接口默认函数实现中使用类似 fn(&self) 的构造?
请问可以举一些例子吗?
谢谢
解决方案
我对 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")
}
推荐阅读
- openapi - Swagger codegen:生成具有正确名称的数组元素
- java - 通过终端使用 jasypt 加密简单字符串
- android - 如何查找 Android 类引入了哪个 API 级别?
- reactjs - 在反应中从另一个钩子调用钩子
- c++ - std::filebuf 打开文件,如果不存在则创建
- python - BeautifulSoup 允许我抓取一些文章,但不能抓取其他文章(来自同一份报纸)
- azure-devops - 为什么是网络。
.config 在发布管道中的文件转换之后存在 - python - 使用 Python 基于现有数据集生成新数据
- adsense - 如何在 SPA(单页应用)的路线更改时调用 AdSense 自动广告?
- wordpress - 更新 wordpress 和插件后出现 Wordpress 错误