# How to implement this function normally?

**URL:** <https://discuss.kotlinlang.org/t/how-to-implement-this-function-normally/13041>\
**Category:** Uncategorized\
**Created:** [June 11, 2019, 9:46am UTC](https://discuss.kotlinlang.org/t/how-to-implement-this-function-normally/13041 "2019-06-11T09:46:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rpuxa](https://avatars.discourse-cdn.com/v4/letter/r/57b2e6/32.png) [@rpuxa](https://discuss.kotlinlang.org/u/rpuxa)\
**Post date:** [June 11, 2019, 9:46am UTC](https://discuss.kotlinlang.org/t/how-to-implement-this-function-normally/13041/1 "2019-06-11T09:46:48Z")

</div>

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  
}

---

<div class="post-metadata">

**Author:** ![pdvrieze](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/pdvrieze/32/1882_2.png) [@pdvrieze](https://discuss.kotlinlang.org/u/pdvrieze)\
**Post date:** [June 12, 2019, 6:10am UTC](https://discuss.kotlinlang.org/t/how-to-implement-this-function-normally/13041/2 "2019-06-12T06:10:11Z")

</div>

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

```auto
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.

---

<div class="post-metadata">

**Author:** ![rpuxa](https://avatars.discourse-cdn.com/v4/letter/r/57b2e6/32.png) [@rpuxa](https://discuss.kotlinlang.org/u/rpuxa)\
**Post date:** [June 12, 2019, 6:45am UTC](https://discuss.kotlinlang.org/t/how-to-implement-this-function-normally/13041/3 "2019-06-12T06:45:41Z")

</div>

I have done it for compact reading from console

```auto
 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
 }
```
