3

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.

1

1 Answer 1

13

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

this is a pretty nice way of using a sealed class, great answer
Still have to see a language that allows so much flexibility while maintaining a strong type system. Kotlin is amazing
there is an error. "One type argument expected for class CurrentValue<T>" in where class defined on CurrentValue : class TextualValue(value: String) : CurrentValue(value) I edited your answer a little.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.