美文网首页Android技术知识Android开发程序员
Kotlin学习笔记之 13 基础操作符run、with、let

Kotlin学习笔记之 13 基础操作符run、with、let

作者: super_shanks | 来源:发表于2019-04-02 15:59 被阅读11次

13.基础操作符run、with、let、also、apply

使用流程
  • T.run和run

    对象的run方法,在方法体中的最后一行可以做返回值,且方法体中的this代表对象本身的引用。

    val str: String = "Boss"
      val result = str.run {
          print(this) // 参数
          69 //区间返回值
      }
    

    直接使用run方法,其实就是class本身调用的run,所以this指向的是class

    val str: String = "Boss"
      val result : Int = run {
          print(this) // 参数  this@class
          69 //区间返回值
      }
    
  • T.let

    run方法一样,也会返回最后一样的值。不同的是引用对象T用的是it而不是this,一般这种情况下,之所以使用it不使用this是由于this用来表示外面的类class

    val str: String = "Boss"
      val result : Int = str.let {
          print(it) // 参数
          print(this) // this@class
          69 //区间返回值
      }
    

    let还有一个比较牛逼的地方,可以用作对null的安全过滤,?.let调用当出现null的时候将不会运行let的方法

    val listWithNulls: List<String?> = listOf("Kotlin", null)
      for (item in listWithNulls) {
            //此处不会打印出null,只会打印出null
          item?.let { println(it) }
      }
    
  • T.also

    跟上面两个方法不同的是,返回对象本身,即不管我们在方法体中做任何操作,在方法体的最后一行返回任何东西,都是返回的T。同时方法体中也是用it来代表对象本身,this代表类class,跟上面的let唯一不同的就是let最终返回的方法体最后一行,而also放回的是对象本身

    val str: String = "Boss"
      val result : String = str.also {
          print(it) // 参数
          print(this) // this@class
          69 //区间返回值
      }
    
  • T.apply

    使用this,不用it。并且返回对象本身。

    val str: String = "Boss"
    val result : String = str.apply {
          print(this) // 参数
          69 //区间返回值
      }
    
  • with(T)

    可以理解成也是class调的方法,跟run方法不同的是,run方法中this代表的是类class,而withthis代表的是T。同时返回的是方法体的最后一行

    val result1 : Int = with(str) {
          print(this) // 接收者
          69 //区间返回值
      }
    
  • 总结

    • 要么只能用this代表自己,要么就是it代表自己,this代表对象所在类
    • alsoapply返回对象本身,letrun返回方法体最后一行。
    • letalsothisitapplyrun只有it

    不用去强记,IDE自带提醒和报错,久而久之,自然会记得。

相关文章

网友评论

    本文标题:Kotlin学习笔记之 13 基础操作符run、with、let

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