KOTLIN convert string to generic type

Viewed 1770

I want to read a line from input and convert it to generic type. something like

fun <T> R() : T {
  return readLine()!!.toType(T)
}

so for R<int>() it will call toInt() for long toLong() etc. how to achieve such a thing? And btw is there a possibility to have a default generic type (C++ has that) in case you want provide one

1 Answers

You can write generic inline function with reified type parameter:

inline fun <reified T> read() : T {
    val value: String = readLine()!!
    return when (T::class) {
        Int::class -> value.toInt() as T
        String::class -> value as T
        // add other types here if need
        else -> throw IllegalStateException("Unknown Generic Type")
    }
}

Reified type parameter is used to access a type of passed parameter.

Calling the function:

val resultString = read<String>()
try {
    val resultInt = read<Int>()
} catch (e: NumberFormatException) {
    // make sure to catch NumberFormatException if value can't be cast
}
Related