Kotlin 中的“by”关键字有什么作用?
Kotlin 通过引入新的关键字“by”来支持设计模式的委派。使用此关键字或委派方法,Kotlin 允许派生类通过特定对象访问接口的所有实现的公共方法。
示例
在示例中,我们将实现另一个类中的基类抽象方法。
interface Base {
//abstract method
fun printMe()
}
class BaseImpl(val x: Int) : Base {
// implementation of the method
override fun printMe() { println(x) }
}
// delegating the public method on the object b
class Derived(b: Base) : Base by b
fun main(args: Array<String>) {
val b = BaseImpl(10)
// prints 10 :: accessing the printMe() method
Derived(b).printMe()
}输出
将产生以下输出
10
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP