您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Kotlin扩展函数和扩展属性怎么声明
## 一、扩展函数的概念与声明
### 1.1 什么是扩展函数
扩展函数(Extension Functions)是Kotlin中一种特殊的函数,它允许在不修改原始类的情况下,为现有类添加新的方法。这种机制打破了传统面向对象设计中类必须通过继承或组合来扩展功能的限制。
### 1.2 基本语法
```kotlin
fun ReceiverType.functionName(parameters): ReturnType {
// 函数体
// 可以使用this访问接收者对象
}
示例:为String类添加一个反转字符串的扩展函数
fun String.reverse(): String {
return this.reversed() // this指代调用该函数的String对象
}
// 使用
val original = "Kotlin"
println(original.reverse()) // 输出:niltoK
ReceiverType?
声明可处理null情况fun String?.safeLength(): Int = this?.length ?: 0
与扩展函数类似,扩展属性允许为现有类添加新的属性(但实际不插入字段,必须通过getter/setter实现)
val ReceiverType.propertyName: PropertyType
get() = /* 返回表达式 */
var ReceiverType.mutableProperty: PropertyType
get() = /* 返回表达式 */
set(value) { /* 设置逻辑 */ }
val String.lastChar: Char
get() = this[length - 1]
var StringBuilder.lastChar: Char
get() = this[length - 1]
set(value) {
this.setCharAt(length - 1, value)
}
// 使用
println("Hello".lastChar) // o
val sb = StringBuilder("Kotlin?")
sb.lastChar = '!'
println(sb) // Kotlin!
val Int.double = this * 2
会报错)import packagename.functionName
当扩展函数与成员函数签名相同时: - 成员函数优先调用 - 可使用相同签名不同返回类型的扩展(但应避免)
fun <T> List<T>.penultimate(): T {
if (size < 2) throw NoSuchElementException()
return this[size - 2]
}
// 使用
val list = listOf(1, 2, 3)
println(list.penultimate()) // 2
class MyClass {
companion object
}
fun MyClass.Companion.printHello() {
println("Hello from companion")
}
// 调用
MyClass.printHello()
替代Java中的静态工具类:
// 代替StringUtils.isEmpty()
fun String.isNullOrBlank(): Boolean = this == null || isBlank()
fun table(init: TableBuilder.() -> Unit): Table {
val builder = TableBuilder()
builder.init()
return builder.build()
}
fun View.show() { this.visibility = View.VISIBLE }
fun View.hide() { this.visibility = View.GONE }
// 使用
myButton.show()
Java调用扩展:实际编译为静态方法
// Java中调用
StringExtKt.reverse("text");
文件注解:使用@file:JvmName
指定类名
@file:JvmName("StringUtils")
package com.example
特性 | 扩展函数 | 扩展属性 |
---|---|---|
声明方式 | fun Type.func() |
val Type.prop |
支持读写 | 不适用 | var声明可变属性 |
实现限制 | 无特殊限制 | 不能有幕后字段 |
典型用途 | 添加操作行为 | 添加计算属性 |
最佳实践建议: 1. 优先用于增强第三方库 2. 避免过度使用导致代码可读性下降 3. 注意与成员函数的命名冲突 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。