KPojo Accessors

This chapter describes the property dynamic accessor provided by Kronos for KPojo at compile time, which supports dynamically accessing or modifying property values based on the property name at runtime, and does not rely on reflection for higher performance, and is recommended.

The Get property accessor of KPojo

In Kronos, we can use KPojo's get property accessor to access the fields of a data table.

kotlin

data class User(
    val id: Int? = null,
    val name: String? = null,
    val age: Int? = null
) : KPojo

val user = User(
    id = 1,
    name = "Kronos",
    age = 18
)

val valueOfId = user["id"] // 1
val valueOfName = user["name"] // "Kronos"
val valueOfAge = user["age"] // 18

result

id -> 1
name -> Kronos
age -> 18
missing field -> null

The Set property accessor of KPojo

In Kronos, we can use KPojo's set attribute accessor to modify the fields of a data table.

kotlin

data class User(
    val id: Int? = null,
    val name: String? = null,
    val age: Int? = null
) : KPojo

val user = User(
    id = 1,
    name = "Kronos",
    age = 18
)

user["id"] = 2 // Immutable values are also modifiable by this accessor
user["name"] = "Kronos" // Immutable values are also modifiable by this accessor
user["age"] = 20 // Immutable values are also modifiable by this accessor

result

user.id == 2
user.name == "Kronos"
user.age == 20

Use these accessors when generic code receives field names at runtime. For map conversion APIs that use the same KPojo field metadata, see 📚Map/KPojo Conversion.