i have 2 questions what is difference between .toS...
# getting-started
m
i have 2 questions what is difference between .toString and as String second question is: can we do both upcasting and downcasting with as keyword?
r
.toString()
is a conversion, whereas
as String
is a cast (it doesn't convert, it falls if the receiver is not a
String
).
You can cast however you want with
as
, but that doesn't mean the cast will always succeed.
m
@Ruckus There is an error in android studio this cast never succeed.If we try unrelated cast.
i am asking which casts can succed always
up to down and down to up can work always?
r
I think you are misunderstanding what casting is. Casting doesn't change the receiver, it just tells the compiler "hey, you may not know it, but this thing is definitely a [whatever you're casting to], so treat it as such." The error is the compiler telling you "I see what you're saying, but I can guarantee there is no possible way this thing is really a [whatever you're casting to], so this cat will always fall."
Casting to a super type will always work, but casting to a sub type will only work if it is that type.
m
can we cast from "any" class to everything
r
You can, but that doesn't mean the cast will succeed.
Copy code
val x: Any = 5
x as String  // falls, x is an Int, not a String
m
ok.I see it is so clear now.Thank you
Lastly is casting more efficient than conversion? ı heard that but i wanted to be sure
r
They're two different things with different purposes. It doesn't make sense to ask which is more efficient. Which one you use depends on what you're trying to do.
1
m
ok.thanks