I know that Kotlin's Android Extensions creates synthetic properties + caching function to replace any need to call findViewById
:
- https://stackoverflow.com/a/46482618/1650674
- https://www.raywenderlich.com/84-kotlin-android-extensions
- https://antonioleiva.com/kotlin-android-extensions/
All of these examples show that the similar java code would look like
private HashMap _$_findViewCache;
...
public View _$_findCachedViewById(int var1) {
if(this._$_findViewCache == null) {
this._$_findViewCache = new HashMap();
}
View var2 = (View)this._$_findViewCache.get(Integer.valueOf(var1));
if(var2 == null) {
var2 = this.findViewById(var1);
this._$_findViewCache.put(Integer.valueOf(var1), var2);
}
return var2;
}
public void _$_clearFindViewByIdCache() {
if(this._$_findViewCache != null) {
this._$_findViewCache.clear();
}
}
What I don't understand is how this prevents potential NPEs? var2 = this.findViewById(var1);
may still return null.
Using the example from that last link:
<TextView
android:id="@+id/welcomeMessage"
...
android:text="Hello World!"/>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
welcomeMessage.text = "Hello Kotlin!"
}
What type is welcomeMessage
? TextView
or TextView?