SadeQ digitALLife
SadeQ digitALLife

Reputation: 1444

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
}

Upvotes: 0

Views: 50

Answers (2)

Adam Dziedzic
Adam Dziedzic

Reputation: 41

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)
}

Upvotes: 0

Jon Adams
Jon Adams

Reputation: 25137

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.

Upvotes: 1

Related Questions