Kotlin: Apply vs With

前端 未结 4 1989
再見小時候
再見小時候 2020-12-12 23:23

What is the difference between with and apply. From what I know the following code does the same thing:

swingElement.apply {
    minWidth = ENABLED_COLUMN_WI         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-13 00:11

    The apply function

    //returns receiver T, T exposed as `this`
    fun  T.apply(block: T.() -> Unit): T 
    

    Description

    The apply function is invoked on a receiver T, which will be exposed as this in the passed lambda expression. The receiver also becomes the result of apply automatically.

    The with function

    //return arbitrary value R, not an extension function, T exposed as `this` 
    fun  with(receiver: T, block: T.() -> R): R 
    

    Description

    The with function, as opposed to all other scope functions (let, run, also, apply), is not defined as an extension function. Instead, the function is invoked with a receiver object as its first argument explicitly. Same as apply, the receiver is exposed as this in the passed lambda. The result of the lambda, i.e. it’s last statement, becomes the result (R) of with.

提交回复
热议问题