What is main reason for having `with` and `apply` ...
# getting-started
i
What is main reason for having
with
and
apply
?
s
image.png
👍 15
💯 4
1
p
apply is really useful for classes that have inappropriate constructors for your use. Imagine you have a class with a zero arg constructor and you want to create it and immediately set some properties. In Java, you'd do something like:
Animal dog = new Animal();
dog.setName("Fido");
dog.setColour("Black");
In Kotlin using apply:
val dog = Animal().apply {
name="Fido"
colour="Black"
}
With is handy when you have some properties of an object that you want to use, but you don't want to keep referring to the parent object: Java:
Animal veryLongAnimalInstance = new Animal()
someMethod(veryLongAnimalInstance.getName(),veryLongAnimalInstance.getColour());
Kotlin:
veryLongAnimalInstance = Animal()
with(veryLongAnimalInstance) {
someMethod(name,colour)
}
👍 2
m
@Paul N amazing and thanks for sharing
👍 1