kotlin 中let 和apply的区别

场景一

private var mLayoutInflater : LayoutInflater? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TabHolder {
        val binding: XXXItemBinding = DataBindingUtil.inflate(mLayoutInflater ?: LayoutInflater.from(parent.context).apply {
            mLayoutInflater = this
        }, R.layout.xxx_item, parent, false)
        return ViewHolder(binding)
    }

场景一中由于DataBindingUtil.inflate第一个参数需要非空参数,所以不能直接使用let{ mLayoutInflater = this}返回的mLayoutInflater,这样就能简单的解答apply返回的是当前闭包,而let返回的是最后一行代码
当然也可以进行如下改造:

private var mLayoutInflater : LayoutInflater? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TabHolder {
        val binding: XXXItemBinding = DataBindingUtil.inflate(mLayoutInflater ?: LayoutInflater.from(parent.context).let{
            mLayoutInflater = it
            it
        }, R.layout.xxx_item, parent, false)
        return ViewHolder(binding)
    }

但是这样显得比较繁琐了,并不值得推荐
再看如下示例

class MyClass {
    fun test() {
        val str: String = "Boss"
        val result = str.xxx {
             print(this) // 接收者
             print(it) // 参数
             69 //区间返回值
        }
        print(result)
    }
}
操作符号 接受者(this) 传参(it) 赋值(result)
T.let() this@Myclass String( "Boss" ) Int( 69 )
T.run() String( "Boss" ) 编译错误 Int( 69 )
T.apply() String( "Boss" ) 编译错误 String( "Boss" )
T.also() this@Myclass String( "Boss" ) String( "Boss" )

场景二

private lateinit var mLocateClient: LocateClient
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mLocateClient = LocateClient(this, lifecycle)
        mLocateClient.start()
}

override fun onDestory() {
        super.onDestory()
        mLocateClient.onDestory()
}

场景二中主要介绍了部分参数依赖Activity的生命周期onCreate方法,但是在其它生命周期中需要调用方法的情景

Thanks

https://juejin.im/post/6844903517023387662

你可能感兴趣的:(kotlin 中let 和apply的区别)