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

243
Vistas
Kotlin Data Class Property: Multiple types

In Kotlin, can a property of a data class have multiple types? For example:

val CurrentValue: Double?|String or val CurrentValue: String|Array?

I cannot find it in the documentation.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Union types are not a thing in Kotlin.

You may use a sealed class instead.

sealed class CurrentValue<T>(val value: T) {
  class TextualValue(value: String) : CurrentValue(value)
  class NumericValue(value: Double) : CurrentValue(value)
}

Which then you can use exhaustive when expressions (similar to switch in other languages) in order to access the value in a type-safe manner:

fun doSomething(value: CurrentValue<*>) {
  
  when(value) {
    is TextualValue -> value.value // is recognised as a String
    is NumericValue -> value.value // is recognised as a Double
  }

}

If creating a type is way too much for you then you can perform a when statement and treat a parameter based on it's type and perhaps normalize it:

fun parseValue(value: Any?): Double? = when(value){
  is Double -> value
  is String -> value.toDoubleOrNull()
  is Int -> value.toDouble()
  else -> null
}
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