KOTLIN convert string to generic type
Asked Answered
V

1

7

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

Vaal answered 25/5, 2020 at 16:50 Comment(0)
G
11

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
}
Groundhog answered 26/5, 2020 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.