How to implement this function normally?

inline fun String.convert(): T {
return when {
“” is T -> this
1 is T -> toInt()
1L is T-> toLong()
’ ’ is T -> first()
true is T -> toBoolean()
else -> fail(“Unknown type”)
} as T

If I understand it correctly you want a “magic” conversion function. This is possible, but works different from how you are putting it:

inline fun <reified T> String.convert(): T = when(T::class) {
    -> this

    -> toInt()

    -> toLong()

    -> first()

    -> toBoolean()

  else -> fail("Unknown type")
} as T

As it all happens at compile time, I do wonder why not use the conversion functions directly. Alternatively you can create an function that takes a class parameter to handle runtime cases. You can even have an inline forwarder that passes a reified type parameter for this.


I have done it for compact reading from console

 fun main() {
     val (integer, long, string) = readFromConsole<Int, Long, String>()

 inline fun <reified T1, reified T2, reified T3> readFromConsole(): Triple<T1, T2, T3> {
     val (first, second, third) = readStrings()
     return Triple(first.convert(), second.convert(), third.convert())

 inline fun <reified T> String.convert(): T {
     return when (T::class) {
         String::class -> this
         Int::class -> toInt()
         Long::class -> toLong()
         Char::class -> first()
         Boolean::class -> toBoolean()
         else -> throw IllegalStateException("Unknown type")
     } as T
1 Like