0

I am new to Kotlin and just started learning it. I came across with and apply functions in Kotlin. I just want to understand the difference between them in the below scenario:

I have a class Person and I assigning values to the properties of its object like this:

val andre = Person().apply {
    name = "Andre"
    company = "Viacom"
    hobby = "losing in ping pong"
}

But this can be done using the with function as well:

val andre = Person()
with(andre){
    name = "Andre"
    company = "Viacom"
    hobby = "losing in ping pong"
}

Now what is the difference between with and apply functions in this context ?

sagar suri
  • 4,351
  • 12
  • 59
  • 122
  • There is a useful comparison table here: https://proandroiddev.com/the-difference-between-kotlins-functions-let-apply-with-run-and-else-ca51a4c696b8. – Oliver Charlesworth Feb 11 '18 at 11:21
  • The closest analogue of `with` is `let`, not `apply`. In your case there's very little difference between `let` and `apply` because you know the target is non-null. – Marko Topolnik Feb 11 '18 at 11:23
  • @MarkoTopolnik, It's more like `run` (the extension method version). Both use a receiver and return the block's return value. `let` doesn't use a receiver. – chris Feb 11 '18 at 11:30
  • @chris True, `let` converts the receiver to the lambda argument. – Marko Topolnik Feb 11 '18 at 11:31

0 Answers0