'Difference between let and apply on returned object
Here is the code I use to dismiss existing fragment. I am able to use let
and apply
.
I read a lot about differences between let
and apply
and I understood that:
- apply modifies existing object that we have
- let creates copy of the object and can modify it. If we exit out of
let
scope the original object is intact. Am I right?
My code is presented in two versions.
private fun prepareQuestionFragment(indexOfMarkerList: Int): QuestionFragment {
childFragmentManager.findFragmentByTag(QuestionFragment.TAG)?.apply {
this as QuestionFragment
this.dismissAllowingStateLoss()
}
return QuestionFragment.newInstance(indexOfMarkerList)
}
private fun prepareQuestionFragment(indexOfMarkerList: Int): QuestionFragment {
childFragmentManager.findFragmentByTag(QuestionFragment.TAG)?.let {
it as QuestionFragment
it.dismissAllowingStateLoss()
}
return QuestionFragment.newInstance(indexOfMarkerList)
}
What is the difference at this case? For me they behaves the same.
Does the let
make a copy of Fragment? If so, we would dismiss copy of fragment and the the original one should stay visible. Am I missing something? Does let
and apply
contains still reference to the object (not copy)?
Solution 1:[1]
let creates copy of the object and can modify it. If we exit out of let scope the original object is intact. Am I right?
No. Java/Kotlin doesn't have a generic concept of copying objects. They can only copy references to the same object.
The main difference in your example is how lambda receives QuestionFragment
object. Lambda in let()
gets QuestionFragment
as its regular argument, by default named as it
. Lambda in apply()
receives this object as its receiver argument, so this
. It's almost a cosmetic difference, it doesn't really differ in the way how it works.
Another difference is that let()
returns the result of the lambda, so in your example the result of dismissAllowingStateLoss()
. apply()
returns the receiver object, so the result of findFragmentByTag()
. You don't use the return value of let()
/apply()
, so this difference is irrelevant in your example.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | broot |