Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

247
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda