美文网首页
Kotlin高阶扩展函数:理解let、with、run、appl

Kotlin高阶扩展函数:理解let、with、run、appl

作者: ModestStorm | 来源:发表于2022-09-27 13:15 被阅读0次

前言

为了方便开发者更加友好的代码编写,kotlin提供了高阶扩展函数let,a l so,with,run,apply。在理解之前,需要我们理解 扩展函数 与 高阶函数 的概念。

扩展函数

kotlin中的扩展函数可以扩展一个类的功能而无需继承该类或者使用装饰者设计模式那样扩展功能,这通过叫做扩展的特殊声明完成。

如我们想为String类型扩展一个打印方法,直接定义一个扩展函数即可,无需通过集成的方式去扩展。

fun String.println() {
      println(this.toString());
  }
        
 "hahah".println();

高阶函数

kotlin支持方法参数的类型是函数或者方法的返回值是函数,我们称这样的函数为高阶函数。

kotlin内部帮我们封装了对象实例的let, also,apply,with高阶函数方便我们使用。

let

let高阶函数的定义,返回函数体中的最后一行代码:

public inline fun <T, R> T.let(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

let高阶函数的使用,代码块中使用it来访问,let返回值是代码块中的最后一行

var textView = TextView(this)

textView.let {
            it.text = "storm"
        }

also

also函数的定义,also返回值为当前调用also的对象实例

public inline fun <T> T.also(block: (T) -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block(this)
    return this
}

also也是通过it函数来访问当前调用also的对象,also函数的返回值是当前实例对象

 var textView = TextView(this)
        textView = textView.also {
            it.text = "storm"
        }

apply

apply的定义:内部使用this访问当前对象,this可省略,返回值是当前对象实例

public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

使用方式

 var textView = TextView(this)
       textView = textView.apply {
            text = "storm"
        }

run

run函数的定义:内部使用this访问,返回值是block代码块的最后一行

public inline fun <T, R> T.run(block: T.() -> R): R {
   contract {
       callsInPlace(block, InvocationKind.EXACTLY_ONCE)
   }
   return block()
}

run函数的使用:内部使用this访问当前对象

textView.run {
            text = "storm"
        }

with

with函数的定义

public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return receiver.block()
}

with函数的使用:内部通过this来访问,返回值是代码块中的最后一行

 with(mTextView){
            this?.text ?:= "haha"
            this?.setTextColor(Color.BLACK)
  }

//带返回值的with
var num =with(textView){
           textView.text = "storm"
           0//返回值
       }

相关文章

网友评论

      本文标题:Kotlin高阶扩展函数:理解let、with、run、appl

      本文链接:https://www.haomeiwen.com/subject/rbxvortx.html