https://kotlinlang.org logo
Title
m

Muhammet Emin Gündoğar

09/05/2021, 10:39 AM
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

Ruckus

09/05/2021, 2:28 PM
.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

Muhammet Emin Gündoğar

09/05/2021, 2:31 PM
@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

Ruckus

09/05/2021, 2:38 PM
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

Muhammet Emin Gündoğar

09/05/2021, 2:40 PM
can we cast from "any" class to everything
r

Ruckus

09/05/2021, 2:41 PM
You can, but that doesn't mean the cast will succeed.
val x: Any = 5
x as String  // falls, x is an Int, not a String
m

Muhammet Emin Gündoğar

09/05/2021, 2:51 PM
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

Ruckus

09/05/2021, 3:07 PM
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

Muhammet Emin Gündoğar

09/05/2021, 3:22 PM
ok.thanks