Kotlin: Apply vs With

前端 未结 4 1988
再見小時候
再見小時候 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:01

    Here are the Similarities and Differences

    Similarities

    With and Apply both accept an object as a receiver in whatever manner they are passed.

    Differences

    With returns the last line in the lambda as the result of the expression.

    Apply returns the object that was passed in as the receiver as the result of the lambda expression.

    Examples

    With

    private val ORIENTATIONS = with(SparseIntArray()) {
        append(Surface.ROTATION_0, 90)
        append(Surface.ROTATION_90, 0)
        append(Surface.ROTATION_180, 270)
        append(Surface.ROTATION_270, 180)
    }
    ORIENTATIONS[0] // doesn't work 
    // Here, using with prevents me from accessing the items in the SparseArray because, 
    // the last line actually returns nothing
    

    Apply

    private val ORIENTATIONS = SparseIntArray().apply {
        append(Surface.ROTATION_0, 90)
        append(Surface.ROTATION_90, 0)
        append(Surface.ROTATION_180, 270)
        append(Surface.ROTATION_270, 180)
    }
    ORIENTATIONS[0] // Works
    // Here, using apply, allows me to access the items in the SparseArray because, 
    // the SparseArray is returned as the result of the expression
    

提交回复
热议问题