Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Data Class Property: Multiple types

Tags:

kotlin

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.

like image 450
markelc Avatar asked Apr 23 '26 13:04

markelc


1 Answers

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<String>(value)
  class NumericValue(value: Double) : CurrentValue<Double>(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
}
like image 185
Some random IT boy Avatar answered Apr 25 '26 18:04

Some random IT boy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!