Kotlin: Apply vs With

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

    "with(here class reference required)" is used for accessing variable of another class but not for method of that class. Now if we want to use variable and method of another class that time we need to use apply(reference.apply{}) Declare a class like below

    class Employee {
        var name:String = ""
        var age:Int = -1
    
        fun customMethod() {
            println("I am kotlin developer")
        }
    }
    

    Now we can access name and age variable of Employee class in onCreate by "with"

    val emp = Employee()
    with(emp) {
        name="Shri Ram"
        age=30
    }
        
    println(emp.name)
    println(emp.age)}
    

    but we cannot access the "customMethod" of Employee class by with so if we need to use variable along with method, then we need to use "apply":

    val emp = Employee()
    emp.apply {
        name="param"
        age=30 
    }.customMethod()
            
    println(emp.name)
    println(emp.age)}
    

    Output of with

    I/System.out: Shri Ram
    I/System.out: 30
    

    Output of apply

    I/System.out: I am kotlin developer 
    I/System.out: param
    I/System.out: 30
    

提交回复
热议问题