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
"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