It has to do with the scope within the curly braces, in all honesty though I generally pick one or the other based on readability. With “it” you can l define the variable to something else so “it” could be defined as “person” if you were working with a Person object for instance. On the other hand “this” cannot be redefined but it can be omitted from the call site so it can make the code more concise but sometimes harder to follow.
data class Person(val name: String, val age: Int) val examplePerson = Person("Yasmine", 21) examplePerson.apply { println("$name is $age") // Yasmine is 21 } examplePerson.also { println("Person's name is ${it.name}") // Person's name is Yasmine }
I tend to use it with Snackbar or Intent like this -
Intent(this, MainActivity::class.java).also { startActivity(it) }
you can use method reference in this case too, .also(::println)
Yup, function references are really nice 😊
Thanks for the Info
@@ashishproc9636 yeah you’re welcome 😊
whats the difference between this and it in this example please can anyone help me ?
It has to do with the scope within the curly braces, in all honesty though I generally pick one or the other based on readability. With “it” you can l define the variable to something else so “it” could be defined as “person” if you were working with a Person object for instance. On the other hand “this” cannot be redefined but it can be omitted from the call site so it can make the code more concise but sometimes harder to follow.
data class Person(val name: String, val age: Int)
val examplePerson = Person("Yasmine", 21)
examplePerson.apply {
println("$name is $age") // Yasmine is 21
}
examplePerson.also {
println("Person's name is ${it.name}") // Person's name is Yasmine
}