August 2017
Intermediate to advanced
440 pages
10h
English
Smart casts also handle other cases, including nullity checks. Let's assume that we have a view variable that is marked as nullable, because we don't know whether or not findViewById will return a view or null:
val view: View? = findViewById(R.layout.activity_shop)
We could use the safe call operator to access view methods and properties, but in some cases we may want to perform more operations on the same object. In these situations, smart casting may be a better solution:
val view: View?
if ( view != null ){
view.isShown() // view is casted to non-nullable inside if code block
}
view.isShown() // error, outside if the block view is nullable
When performing null checks like this, the compiler automatically casts ...
Read now
Unlock full access