'How can I type alias multiple Kotlin types into a single type
Suppose I have variable which can be Int, String or Float. I want to create a generic type using type alias that includes all the above 3 types. Something like
typealias customType = Int || String || Float
Solution 1:[1]
Answering your comment to previous answer:
Unfortunately, Kotlin does not support multiple generic constraints and union types currently.
The only way is to use Any or inheritance.
sealed interface StringOrFloat
data class StringType(val field: String): StringOrFloat
data class FloatType(val field: Float): StringOrFloat
fun mapToStringOrFloat(value: Any): StringOrFloat {
return when(value) {
is Float -> FloatType(value),
is String -> StringType(value)
else -> ... // you can throw exception here
}
}
val value: StringOrFloat = mapToStringOrFloat(someValue)
Solution 2:[2]
Use Any as the datatype like:
private lateinit var value: Any
Any is superclass of all the datatypes like String, Int, Float etc and in future, you can assign any value to it like:
value = "hello"
or
value = 6
or
value = 6F
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
