I am looking at the scope functions in Kotlin (let, run, with, apply, also) and I have a doubt between apply and with. I've read that apply is used when the value needs to return itself, but what does this mean? Since seeing the codes is almost the same:
val mediaItem = MediaItem("Title 14", "", MediaItem.Type.PHOTO).apply {
title = "Title 15"
imageUrl = ""
typeElement = MediaItem.Type.VIDEO
}
with(mediaItem) {
title = "Title 16"
imageUrl = ""
typeElement = MediaItem.Type.VIDEO
}
The only thing I see is that with needs the object to be used and with apply we use it from this object, but it is not very clear to me, let's see if any of you can explain it to me.
Indeed they are very similar, the main differences are:
with
doesn't need an object to be called on, whereas itapply
does.apply
is executed on the object reference, whilewith
passing it as an argument.with
returns a result.