Does casting actually mutate an Object?
I have something like this (simplified):
val cDeferred = CompletableDeffered<X>()
launch{
//Do things and complete cDeffered
}
return cDeferred as Deferred<Y> //does this cast count as mutating a shared object?
I think the answer is “no, the object stays the same”.
You are correct, the object does not change during a cast.
Just like if I gave you a small disc shaped object, you wouldn’t know what it is or how to use it. If I then told you that the object was a voice assistant (i.e. Amazon Alexa), you would know how to interact with it.
Telling you what kind of object a thing is so you can use it properly is essentially what casting does for your code.
In the case of casting generics, you do have to worry about variance. It’s a common mistake to treat List<Animal>
as a supertype to List<Dog>
just because Animal
is a supertype Dog
.
Still, casting one generic type to another, when done properly, does not change the object itself or the actual generic type for the object.
4 Likes