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
)
}
如何訪問 B 類和 C 類的資料?
uj5u.com熱心網友回復:
你可以這樣訪問
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
)
}
//輸出
Hello, world!!!
A(type=1, data=String)
B(name=B, phone=123456789)
C(name=c, phone=987654321)
uj5u.com熱心網友回復:
我會為嵌套類創建一個父類:
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)
}
}
uj5u.com熱心網友回復:
經過幾次嘗試,我現在得到了答案..
val b:AB = list[position].data as AB
val c:AC = list[position].data as AC
感謝大家的快速回答和討論。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/487686.html
