Home > Enterprise >  How access value from data class which is inside a data class
How access value from data class which is inside a data class

Time:06-09

data class A(
  val type: Int,
  val data: Any
) {
  data class B(
    val name: String,
    val phone: String
  )
  data class C(
    val name: String,
    val phone: String
  )
}

How to access data of class B and C??

CodePudding user response:

You can access like this

fun main() {
    println("Hello, world!!!")
    val a = A(
        type = 1,
        data = "String"
    )
        println("$a")
        
        val b = A.B(
         name = "B",
         phone = "123456789"   
        )
        println("$b")
        
        val c = A.C(
         name = "c",
         phone = "987654321"   
        )
        
        println("$c")


}

data class A(
  val type: Int,
  val data: Any
) {
  data class B(
    val name: String,
    val phone: String
  )
  data class C(
    val name: String,
    val phone: String
  )
}

//Output

Hello, world!!!
A(type=1, data=String)
B(name=B, phone=123456789)
C(name=c, phone=987654321)

CodePudding user response:

I would create a parent class for the nested classes:

data class A(
  val type: Int,
  val data: Data
) {

  abstract class Data(
    open val name: String,
    open val phone: String
  )

  data class B(
    override val name: String,
    override val phone: String,
    val moreInfo: String
  ): Data(name, phone)

  data class C(
    override val name: String,
    override val phone: String,
    val otherInfo: String
  ): Data(name, phone)

}

val list = listOf(
  A(1, A.B("name B1", "phone 1", "more info 1")),
  A(2, A.B("name B2", "phone 2", "more info 2")),
  A(3, A.C("name C1", "phone 3", "other info 1")),
  A(3, A.B("name B3", "phone 4", "more info 3"))
)

// no casting necessary for properties of the data class "Data"
println(list[1].data.name)
println(list[2].data.phone)

// casting necessary for properties in the data classes "B" and "C
println((list[1].data as A.B).moreInfo)
println((list[2].data as A.C).otherInfo)

// (smart) casting with if clause
for (item in list) {
  if (item.data is A.B) {
    println(item.data.moreInfo)   // smart casting
  } else if (item.data is A.C) {
    println(item.data.otherInfo)   // smart casting
  } else {
    // maybe raise an exception here
  }
}

// (smart) casting with when clause
for (item in list) {
  when (item.data) {
    is A.B -> println(item.data.moreInfo)
    is A.C -> println(item.data.otherInfo)
  }
}

CodePudding user response:

i got the answer now afer few tries ..

val b:A.B = list[position].data as A.B

val c:A.C = list[position].data as A.C

Thanks every one for your quick answer and discussoin.

  • Related