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) {
  Any::class,
  CharSequence::class,
  String::class 
    -> this

  Int::class 
    -> toInt()

  Long::class
    -> toLong()

  Character::class
    -> first()

  Boolean::class
    -> 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.

2 Likes

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())
 }


 @Suppress("IMPLICIT_CAST_TO_ANY")
 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