多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 1. 前言 所谓扩展函数也就是在原本类的基础上增加一些新的方法。我们知道在`Java`中`String`等类定义为`final`也就是不允许修改和继承,那么如果我们期望对这些类新增一些方法的时候,在`Java`中无法做到,而在`Kotlin`中却提供了**扩展**来实现。也就是说,在`Kotlin`的扩展不仅可以用于自定义类,也可用于`String`等其它类。 而这种方式其实在`Kotlin`语言基础中也使用过,类似于`JavaScript`中的原型。 # 2. 使用 ## 2.1 简单扩展函数 比如下面的两个简单的案例: ~~~ fun String.doSomething(count: Int = 1): String{ return this.repeat(count) } fun Any.showInfo(): Any{ println(this) return this; } fun main() { "abc".showInfo() "abc".doSomething(2).showInfo() } ~~~ 结果: ``` abc abcabc ``` ## 2.2 泛型扩展函数 但是,当我们使用: ~~~ "abc".showInfo().doSomething(2).showInfo() ~~~ 却不支持,因为`showInfo`函数返回的是`Any`类型,而`doSomething`针对的是字符串类型,前面的`Any`类型并不能保证就一定是字符串类型。所以这里可以使用泛型来解决这个问题。比如下面的修改: ~~~ fun String.doSomething(count: Int = 1): String{ return this.repeat(count) } fun <T> T.showInfo(): T{ println(this) return this; } fun main() { "abc".showInfo().doSomething(2).showInfo() } ~~~ 结果和上面的保持一致。这类扩展函数叫做**泛型扩展函数**,通常具有更加广阔的使用空间。且在`Kotlin`的标准库函数中,广泛使用了这类函数,比如`let`函数: ~~~ public inline fun <T, R> T.let(block: (T) -> R): R { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return block(this) } ~~~ ## 2.3 可空扩展函数 这里还是继续对前面定义的函数进行可空的扩展,这里设置一个默认的打印值: ~~~ fun <T> T?.showInfo(default: String = "对象为空"): T?{ println(this ?: default) return this; } ~~~ 结果: ``` 对象为空 ```