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
CodePudding user response:
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 class 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)
CodePudding user response:
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