lem0nify
lem0nify

Reputation: 793

How to overload function with different return types and the same parameters in Kotlin?

I want to overload function with the same parameters (or without parameters at all) and different return types. Correct implementation should be chosen by the type of variable I assign returning value of a function to.

The only way to do this I found is using reified generics and comparing KClass'es:

inline fun <reified T: Any> read(): T {
    return read(T::class)
}

@Suppress("UNCHECKED_CAST")
fun <T: Any> read(t: KClass<T>): T {
    return when (t) {
        Int::class -> readInt() as T
        UInt::class -> readUInt() as T
        String::class -> readString() as T
        // ...
        else -> throw Exception("Unsupported type")
    }
}

fun readInt(): Int {
    // ...
}

fun readUInt(): UInt {
    // ...
}

fun readString(): String {
    // ...
}

The problem with this approach is that the compiler and IDEA are not smart enough to determine types at compile time for which there is no implementation. The most I can do is throw a runtime exception:

val int: Int = read()
val string: String = read()
val double: Double = read()
//                   ^^^^ No compile-time error here

Maybe I'm missing something and there is more "correct" way of doing this?

Upvotes: 2

Views: 1380

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198024

Maybe I'm missing something and there is more "correct" way of doing this?

No. You cannot do this at all. You must name the methods differently.

Upvotes: 4

Related Questions