简体   繁体   中英

cast an object into specific class depend on when called

I have a class that one of properties can has 2 different types, How can I cast that variable to one of those classes that I want?

    class myObject{
        var type: Int
        var meta: Any? = null }

   var myobject:myObject=myObject()
        if(myobjetc.type ==1){
val myObject = (myobjetc.meta) as ObjectA
 Log.e("log",myObject.name)
}
        if(myobjetc.type ==2){
val myObject = (myobjetc.meta) as ObjectB
 Log.e("log",myObject.number)
}

problem is that it cant cast.

EDITED

class ObjectB: GsonBaseModel() {
var name: String? = null
}

    class ObjectA: GsonBaseModel() {
var number: Int? = null
}

You're almost there. Either check for null, or better yet, use is or when and is

// as:
if(myobject.meta as ObjectA != null) Log.e("log", myobject.meta.name)
if(myobject.meta as ObjectB != null) Log.e("log", myobject.meta.number)

// is:
val meta = myobject.meta
if (meta is ObjectA) Log.e("log", meta.somePropertyOfObjectA)
if (meta is ObjectB) Log.e("log", meta.somePropertyOfObjectB)

// when:
when (myobject.meta) {
    is ObjectA -> Log.e("log", myobject.meta.name)
    is ObjectB -> Log.e("log", myobject.meta.number)
    else -> throw Exception()
}

However, this only works if the original type makes sense. If meta is of class ObjectC, and neither ObjectA nor ObjectB inherit from it, then it won't help. Without seeing your class code though, we can't help you there.

But if that is the case, you may want to revisit your class design or code flow if the above won't work for you.

EDIT: After the class info was added to the Question, it looks like you'll want to the first option, the unsafe cast via as with a null check.

It looks like what you need is a sealed class

sealed class Model() : GsonBaseModel()

class TypeA(val number: Int?) : Model()
class TypeB(val name: String?) : Model()

when (myObject) {
    is TypeA -> log(myObject.number)
    is TypeB -> log(myObject.name)
}

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