https://kotlinlang.org logo
#android
Title
# android
a

Ayden

01/12/2018, 10:21 AM
What is the
view as Button
means?
v

vincent.desmet

01/12/2018, 10:23 AM
it casts the ‘view’ object to a Button, like
(Button) view
does in Java
m

menegatti

01/12/2018, 10:24 AM
and if
view
cannot be cast to
Button
it will throw an exception
a

Ayden

01/12/2018, 10:26 AM
Can I do it without using view as Button? Instead, I just defined like
val btnSelected = Button
.
m

menegatti

01/12/2018, 10:27 AM
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

Benoît

01/12/2018, 10:28 AM
If you know java, it's like doing
Button b = (Button) yourView;
a

Ayden

01/12/2018, 10:28 AM
Sorry, it might seem like a dumb question. I just want to understand what is the usage.
m

menegatti

01/12/2018, 10:30 AM
no issues… the point is just that
as X
is the way to cast an object to another type
a

Ayden

01/12/2018, 2:11 PM
That line of code is mean it passes the view to the button? Am I right?
m

menegatti

01/12/2018, 2:14 PM
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

Ayden

01/12/2018, 2:42 PM
Need some time to digest.
Thank you so much @menegatti
4 Views