Kotlin Android Extensions and Variables
Before Kotlin, Android developers have to store the Activity Views reference in a variable like this:
Button fooBtn = (Button) findViewById(R.id.btn_foo)
to reduce the number of boiler room code and the number of calls findViewById
.
With the introduction of the Kotlin Android Extensions, we can reference the same button simply by using:
btn_foo
Questions:
- Is there a link
btn_foo
to link to the saved button or is it callingfindViewById
every time? - Are developers still using storage variables to
btn_foo
improve application performance, or are they just using it directly in their code?
Edit: There is clarification on how extensions work, however this is still a little unclear.
source to share
One of the developers of the Kotlin Android Extension (KAE) Igor Kucherenko confirmed that:
-
KAE will keep the link to the view after the first call, instead of being used
findViewById
all the time. This only works forActivities
andFragments
. -
KAE will not cache data and will use it
findViewById
every time for any other element (exceptActivity
/Fragment
).
So, if you are going to initialize ViewHolder
:
class FooViewHolder(view: View): RecyclerView.ViewHolder(view) {
fun bind(day: FooItem.Day) {
btn_foo.text = day.title
}
}
Decompile the Java call would look like:
((Button)this.itemView.findViewById(R.id.btn_foo)).setText((CharSequence)day.getTitle());
what exactly do you want to avoid.
Developers may be aware of this.
Conclusion : fill in the KAE without any additional variables, but only for your Activitiies
/ Fragments
.
source to share