Hyzam
Hyzam

Reputation: 183

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

Upvotes: 3

Views: 2933

Answers (2)

Steyrix
Steyrix

Reputation: 3236

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)

Upvotes: 2

Abu bakar
Abu bakar

Reputation: 881

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

Upvotes: 0

Related Questions