上一篇博客 【Kotlin】扩展函数 ( 扩展函数简介 | 为 Any 超类定义扩展函数 | private 私有扩展函数 | 泛型扩展函数 | 标准函数 let 函数是泛型扩展函数 ) 中 , 介绍了给 现有类 定义 扩展函数 , 此外还可以 给现有类定义 扩展属性 ;
为现有类定义 扩展属性 语法格式为 :
val 现有类类名.扩展属性名: 扩展属性类型
get() = {}
var 现有类类名.扩展属性名: 扩展属性类型
get() = {}
set() = {}
代码示例 : 在该代码中 , 为 String 类型定义了 扩展属性 extAttribute , 由于是 val 只读变量 , 因此必须在其 setter 函数 中进行初始化变量 , 并且 不能提供 setter 函数 ;
val String.extAttribute: Int
get() {
return 10
}
fun String.addStr(str: String): String {
println("this = $this, string = $str")
return this + str
}
fun main() {
println("123".addStr("abc"))
println("123".extAttribute)
}
执行结果 :
this = 123, string = abc
123abc
10
之前讲的定义扩展函数 , 扩展属性 , 都是为 非空类型 定义的 ,
如果要为 可空类型 定义扩展函数 , 则需要在 扩展函数 中 处理时 , 要多考虑一层 接收者 this 为空 的 情况 ;
注意下面的调用细节 :
可空类型实例对象?.非空类型扩展函数
可空类型实例对象.可空类型扩展函数
代码示例 :
fun String?.addStr(str: String): String {
if (this == null) {
println("this = $this, string = $str, 接收者为空")
return str
} else {
println("this = $this, string = $str, 接收者不为空")
return this + str
}
}
fun main() {
var nullString: String? = null
println("123".addStr("abc"))
println(nullString.addStr("abc"))
}
执行结果 :
this = 123, string = abc, 接收者不为空
123abc
this = null, string = abc, 接收者为空
abc
如果 扩展函数 只有 一个参数 , 并且在 扩展函数 定义时 使用了 infix 关键字修饰 , 在调用该扩展函数时 , 可以省略 接收者与函数之间的点 和 参数列表的括号 ;
调用 使用 infix 关键字修饰 的 单个参数扩展函数 :
接收者 函数名 函数参数
也可以使用 传统方式调用 :
接收者.函数名(函数参数)
Map 中 创建 的 Pair 实例对象 的 to 函数 , 就是 被 infix 修饰的 泛型扩展函数 , 最终产生的是 Pair 实例对象 ;
/**
* 从this和[that]创建类型为[Pair]的元组。
*
* 这对于创建噪音更少的[Map]字面量很有用,例如:
* @sample samples.collections.Maps.Instantiation.mapFromPairs
*/
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
代码示例 :
infix fun String.addStr(str: String): String {
return this + str
}
fun main() {
println("123".addStr("abc"))
// 简略写法如下
println("123" addStr "abc")
}
执行结果 :
123abc
123abc
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有