GreenJay
GreenJay

Reputation: 93

How to get/set value of any fields from data class? (in Kotlin)

I want to take values from data class in kotlin. For example, I have data class

data class DocData(
val i:Int=3,
val s:String="test",
val d:Double=0.2) 

and I want to get something like that

fun checkTypesAndValues() {
    val docData = DocData()
    val fields = docData.javaClass.declaredFields
    for (i in 0..fields.lastIndex) {
        val f = fields[i]
        when (f.type) {
            is Int -> System.out.println(f.value)
            is String -> System.out.println(f.value)
            is Double -> System.out.println(f.value)
        }
    }
}

Upvotes: 1

Views: 2569

Answers (1)

Marvin
Marvin

Reputation: 14415

You can use Kotlin reflection to get all properties with their value, e.g.:

import kotlin.reflect.full.declaredMemberProperties

data class DocData(val i: Int = 3, val s: String = "test", val d: Double = 0.2)

fun main() {
    val docData = DocData()
    docData.javaClass.kotlin.declaredMemberProperties.forEach {
        with(it) {
            println("$returnType: $name = ${get(docData)}")
        }
    }
}

Output:

kotlin.Double: d = 0.2
kotlin.Int: i = 3
kotlin.String: s = test

You will need to add the kotlin-reflect dependency:

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-reflect</artifactId>
    <version>${kotlin.version}</version>
</dependency>

Upvotes: 1

Related Questions