kotlin扩展函数
class Kt23 {
}
fun Kt23.addExfun(name: String) {
println(name)
}
fun String.showss() {
println(this)
}
fun Any.zhaoCai(){
println(this)}
public fun File.readLines(charset: Charset = Charsets.UTF_8): List<String> {
val result = ArrayList<String>()
forEachLine(charset) { result.add(it); }
return result
}
fun main() {
Kt23().addExfun("啊啦啦啦啦啦")
"死死".showss()
"发发".zhaoCai()
println(File("C:\\Users\\smile\\Desktop\\需求记录.txt").readLines())
}
Kotlin泛型扩展函数
fun <T> T.showContentInfo() {
println(if (this is String) "你的字符串长度是${this.length}" else "你的内容是${this}")
}
fun <T> T.showTime() {
println("调用时间是${System.currentTimeMillis()}")
}
fun <T> T.showType() {
println(
when (this) {
is String -> "String类型"
is Boolean -> "Boolean类型"
is Char -> "Char类型"
is Int -> "Int类型"
else -> "其他类型"
}
)
}
fun main() {
"圆明园".showContentInfo()
34.showContentInfo()
"快乐星球".showTime()
"花花".showType()
true.showType()
}
kotlin自定义内置函数(泛型扩展函数+匿名函数+内联)
private inline fun <T, O> T.mLet(lambda: (T) -> O): O {
return lambda(this)
}
fun main() {
println("嘘嘘嘘".mLet {
it
false
})
}
inline 我们的函数是高阶函数,所有用到内联,做lambda的优化,性能提高
fun<T,O> 在函数中申明两个泛型,函数泛型,T输入,O输出
T.mlet 对T类型进行函数扩展,扩展的函数名称是mLet,所有的类型都可以是同mLet函数
lambda:(T) -> O 匿名函数,T输入,O输出
:O O类型会根据用户的最后一行返回类型而定
lambda(this) T进行函数扩展,在整个扩展函数里面,this==T本身
kotlin扩展属性和扩展函数结合
val String.infoName get() = "名字:${this}"
fun String.showPrint(){
println("调用时间${System.currentTimeMillis()}:${this}")}
fun main() {
"吴尊".infoName.showPrint()
}
kotlin 可空类型的扩展函数
fun String?.getInfoName(defalutName: String) = println(this ?: defalutName)
fun String?.getInfoName2(defalutName: String) {
println(if (this == null) defalutName else this)
}
fun main() {
var name: String? = null
name.getInfoName("你是空的呀!!!")
name = "你幼稚了"
name.getInfoName2("你是空的呀!!!")
}