[Kotlin] Summary of let, with, run, apply, and also functions

1. let function

object.let{
    
    
   it.todo()//在函数体内使用it替代object对象去访问其公有的属性和方法
   it.todo()...
}

//另一种用途 判断object为null的操作
object?.let{
    
    //表示object不为null的条件下,才会去执行let函数体
   it.todo()
}

2.With function

适用于调用同一个类的多个方法时,可以省去类名重复,直接调用类的方法即可,经常用于Android中RecyclerView中onBinderViewHolder中,数据model的属性映射到UI上

  1. First judge empty here, and then take out the corresponding data
    Insert picture description here
  2. with comes with a null, and the call does not need to write item and it
    Insert picture description here

3.run function

适用于let,with函数任何场景。因为run函数是let,with两个函数结合体,准确来说它弥补了let函数在函数体内必须使用it参数替代对象,在run函数中可以像with函数一样可以省略,直接访问实例的公有属性和方法,另一方面它弥补了with函数传入对象判空问题,在run函数中可以像let函数一样做判空处理

  1. Before joining
    Insert picture description here
  2. After joining
    Insert picture description here

4. Apply

整体作用功能和run函数很像,唯一不同点就是它返回的值是对象本身,而run函数是一个闭包形式返回,返回的是最后一行的值. It is based on this difference that its applicable scenarios are slightly different from the run function. Apply is generally used when an object instance is initialized, and properties in the object need to be assigned. Or when you dynamically inflate an XML View, you need to bind data to the View, which is very common. Especially in our development, there will be some data models that need to be used in the process of conversion and instantiation of View models.
Insert picture description here

5.Also

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_38304672/article/details/111185825