简体   繁体   中英

How to cast super class object to sub class object in Kotlin?

Here I am trying to converting superclass object to subclass. I am getting the runtime error as "class can not be cast".

Eg:

class Animal {}
class Cat : Animal() {}

class abc {
fun abcd(): Animal {
    return Animal()
}

fun getData() {
    val cat: Cat = abcd() as Cat     //Giving me runtime error.
}
}

Here I am trying to converting superclass object to subclass. I am getting the runtime error as "class can not be cast".

Eg :

class Animal {}
class Cat : Animal() {}

class abc {
fun abcd(): Animal {
    return Animal()
}

fun getData() {
    val cat: Cat = abcd() as Cat     //Giving me runtime error.
}
}

Here I am trying to converting superclass object to subclass. I am getting the runtime error as "class can not be cast".

Eg :

class Animal {}
class Cat : Animal() {}

class abc {
fun abcd(): Animal {
    return Animal()
}

fun getData() {
    val cat: Cat = abcd() as Cat     //Giving me runtime error.
}
}

I know this is an old question, but it's the first Google hit for the search "Kotlin how to cast superclass to subclass", so for prosperity:

How to cast to subcalss in Kotlin
use the "as" keyword as in the original question:

if(animal is Cat) {
    Cat cat = animal as Cat
}

The original question Short answer, you can't cast a superclass object to a subclass object . Casting only changes the type of the reference to the object, the object itself remains unchanged.

The Animal class in the question should almost certainly be marked as abstract. That way there's no possibility to accidentally instantiate non-specific animals, which is what happens in the question and causes the exception.

An Animal reference variable can absolutely be cast to a Cat, provided the object it references is a Cat. But in the question a non-specific Animal is instantiated, and then later attempted to cast to a Cat, but as it is not referencing a Cat object, this understandably throws an exception.

So unlike, say, casting an Int to a Double where the cast seemingly changes the type of the object, casting object references doesn't actually " change " the object, only how finely-grained your reference to it is.
Casting cannot turn a Dog into a Cat, it can only change you from examining an animal as a generic Animal, viewing properties commont to ALL animals, to examining it as a Cat or a Dog and additionally having access to the properties only Cats or Dogs have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM