Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

255
Vistas
Using kotlin-reflect to find the data type of data class's properties

Given a simple data class like:

data class TestSimple(
    val country: String,
    var city: String? = null,
    var number: Int? = null,
    var code: Long? = null,
    var amount: Float? = null,
    var balance: Double? = null
)

Is there any way I can use kotlin-reflect to find the data type of the properties? I got all the properties via:

val allFields = this::class.declaredMemberProperties.map {
    it.name to it
}.toMap()

I only got as far as allFields["number"].returnType which returns a KType. I couldn't figure out a way to check if a KType is Int or Long.

I am trying to avoid the code I currently use to cast the incoming JSON numeric data to appropriate data type:

fun castToLong(value: Any): Long {
    val number = try {
        value as Number
    } catch (e: Exception) {
        throw Exception("Failed to cast $value to a Number")
    }
    return number.toLong()
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

First, you can use some library to parse JSON to actual types. Jackson has good Kotlin support. If you don't want to use library, to determine type of parameter you can use this snippet:

import java.time.OffsetDateTime
import kotlin.reflect.KClass
import kotlin.reflect.full.declaredMemberProperties

data class UpdateTaskDto(
        val taskListId: Long,
        val name: String,
        val description: String? = null,
        val parentTaskId: Long? = null,
        val previousTaskId: Long? = null,
        val dateFrom: OffsetDateTime? = null,
        val dateTo: OffsetDateTime? = null,
        val dateOnlyMode: Boolean? = false
) {
    fun test() {
        this::class.declaredMemberProperties.forEach { type ->
            println("${type.name} ${type.returnType.classifier as KClass<*>}")
        }
    }
}

As a result of calling test method, I got:

dateFrom class java.time.OffsetDateTime
dateOnlyMode class kotlin.Boolean
dateTo class java.time.OffsetDateTime
description class kotlin.String
name class kotlin.String
parentTaskId class kotlin.Long
previousTaskId class kotlin.Long
taskListId class kotlin.Long
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda