kotlin常用的扩展函数

327 阅读1分钟

参考自:# Kotlin指南(一)
参考自:【Android】Kotlin 顶级函数的"顶级"理解

扩展函数

描述:koltlin的扩展函数是一种特殊的函数,允许在不修改原始类定义的情况下向现有类添加新的函数.实际上是在现有类中添加了一个static final方法,在使用时,将需要扩展的类作为第一个参数传入.实例如下

fun String.hello(str: String): String{
    return "hello" + str + this.length
}
 
fun String.hello1(str: String): String{
    return "hello$str"
}

经过反编译如下:

public final class ExtensionTestKt {
   @NotNull
   public static final String hello(@NotNull String $receiver, @NotNull String str) {
      Intrinsics.checkParameterIsNotNull($receiver, "$receiver");
      Intrinsics.checkParameterIsNotNull(str, "str");
      return "hello" + str + $receiver.length();
   }
 
   @NotNull
   public static final String hello1(@NotNull String $receiver, @NotNull String str) {
      Intrinsics.checkParameterIsNotNull($receiver, "$receiver");
      Intrinsics.checkParameterIsNotNull(str, "str");
      return "hello" + str;
   }
}

前言实例代码:

class TestBean {
    var name: String = "xuyisheng" 
    var age: Int = 18 
}

1.let

函数体内使用it代替本对象.返回值为函数最后一行或者return指定的表达式.

val test = TestBean()
val resultLet = test.let { 
    it.name = "xys" it.age = 3 println("let内部 $it") it.age
}
println("let返回值 $resultLet")

2.run

函数体内使用this代替本对象.返回值为函数最后一行或者return指定的表达式.

val test = TestBean()
val resultRun = test.run { 
    name = "xys" age = 3 println("Run内部 $this") age 
} 
println("run返回值 $resultRun")

3.also

函数内使用it代替本对象,返回值为本对象

val test = TestBean()
val resultAlso = test.also { 
    it.name = "xys" it.age = 3 println("also内部 $it") it.age 
}
println("also返回值 $resultAlso")

4.apply

函数体内使用this代替本对象,返回值为本对象

val test = TestBean()
val resultApply = test.apply { 
    name = "xys" age = 3 println("apply内部 $this") age
} 
println("apply返回值 $resultApply")

5.takeif

条件为真返回对象本身否则返回null

val test = TestBean()
test.age = 33 
val resultTakeIf = test.takeIf {
    it.age > 3 
} 
println("takeIf $resultTakeIf")

6.takeUnless

条件为真返回null否则返回对象本身

val test = TestBean()
val resultTakeUnless = test.takeUnless { 
    it.age > 3 
}
println("takeUnless $resultTakeUnless")

7.with

with比较特殊,不是以扩展方法的形式存在,而是一个顶级函数,传入参数为对象,函数内使用this代替对象.返回值为函数最后一行或者return指定表达式.

val test = TestBean()
val resultWith = with(test) { 
    name = "xys" age = 3 println("with内部 $this") age 
} 
println("with返回值 $resultWith")