What is the `view as Button` means?
# android
a
What is the
view as Button
means?
v
it casts the ‘view’ object to a Button, like
(Button) view
does in Java
m
and if
view
cannot be cast to
Button
it will throw an exception
a
Can I do it without using view as Button? Instead, I just defined like
val btnSelected = Button
.
m
it really depends on your code
I assume this is a
clickListener
and you’re using the
view
passed as a parameter
so you you have to cast
b
If you know java, it's like doing
Button b = (Button) yourView;
a
Sorry, it might seem like a dumb question. I just want to understand what is the usage.
m
no issues… the point is just that
as X
is the way to cast an object to another type
a
That line of code is mean it passes the view to the button? Am I right?
m
no
it is a cast
as
means “from this point treat this object type as the type of the cast”
val btnSelected = view as Button
val
means that the field
btnSelected
is read-only
=
causes
btnSelected
to be set to
view
view as Button
forces
view
to be treated as a
Button
instead of
View
a
Need some time to digest.
Thank you so much @menegatti