Step into Kotlin - 18 - Extension 与 this
来源:互联网 发布:网络直播打赏 编辑:程序博客网 时间:2024/05/20 18:41
目录
- Extension 与 this
- Extension
- 概念
- 扩展类的行为
- 扩展类的成员
- 扩展伴生类
- this
- Extension
- Extension 与 this
摘要
扩展方法,扩展成员,扩展伴生类,this 表达式
Extension 与 this
Extension
概念
- Extension 用于对类的行为或者属性进行拓展(包括内置的类)。
- 当扩展的行为或属性与类内部定义的行为或属性重名时,扩展功能无效。
扩展类的行为
定义一个类
class Num(var x: Int) { fun add(y: Int) { x += y } fun foo() { println("foo in Num") }}
扩展类
fun Num.add(x: Int, y: Int) { this.x += x + y}
使用扩展的行为
var n: Num = Num(10)n.add(1, 3)
扩展类的成员
为 List 类添加一个成员
val <T> List<T>.second: T get() = get(1)
使用扩展的成员
val l: List<Int> = listOf(1, 2, 3)println(l.second) // 2
扩展伴生类
class MyClass { companion object {}}class MyClass { companion object {}}MyClass.foo()
this
class A { // 隐式标签 @A fun bar(){ val t = this //类的成员,表示当前对象 } inner class B { // 隐式标签 @B // 扩展类的行为 fun Int.foo() { // 隐式标签 @foo val a = this@A // A's this val b = this@B // B's this // 没有限定符时,表示当前所在的最小范围 val c = this // foo()的接收器,这里是数字 10 val c1 = this@foo // foo()的接收器,这里是数字 10 val funLit = { -> val d = this // funLit 的接收器,这里是 Function0<Unit> } val funLit2 = { s: String -> val d1 = this// funLit2 的接收器,这里是 Function1<String, Unit> } } fun info() { 10.foo() } }}A().B().info()
0 1
- Step into Kotlin - 18 - Extension 与 this
- Step into Kotlin - 12 - Object 与枚举
- Step into Kotlin - 23 - 与 Java 交互
- Step into Kotlin
- Step into Kotlin - 03 - 变量,常量与表达式
- Step into Kotlin - 16 - Data 类与 When 表达式
- Step into Kotlin - 01 - 入门
- Step into Kotlin - 02 - 数据类型
- Step into Kotlin - 04 - 函数
- Step into Kotlin - 06 - 异常
- Step into Kotlin - 08 - 数组
- Step into Kotlin - 09 - 集合
- Step into Kotlin - 11 - 类
- Step into Kotlin - 13 - 包
- Step into Kotlin - 14 - 继承
- Step into Kotlin - 15 - 注解
- Step into Kotlin - 17 - 泛型
- Step into Kotlin - 22 - Xml
- 改进基于优先队列的最短路径搜索『洪水流思想的体现』
- ofbiz myeclipse 配
- 在Chrome调试JavaScript代码以及审查元素各个tab说明
- ofbiz 购物样式 ecommain.css
- Secure Delivery Center的许可证管理
- Step into Kotlin - 18 - Extension 与 this
- 解决WorkBench执行更新语句时【1175 SQLSTATE: HY000 (ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE)】
- 从零开始搭建hadoop分布式集群环境:(二)安装JDK
- 03-树3. Tree Traversals Again (25)
- 程序员的能力拓展模型
- product_store_shipment_meth
- 仿Google分页的经典案例
- POJ Gold Balanced Lineup
- 努力和上进不是为了做给别人看,而是为了不辜负自己