Home > Enterprise >  Break a "when" on a class type argument into several functions
Break a "when" on a class type argument into several functions

Time:08-17

Let's consider the following function :

inline fun <reified T : Any> dispatch() = when (T::class) {
    String::class -> println("I'm a String")
    Float::class -> println("I'm a Float")
    else -> println("I'm something else")
}

Is there a way to break it into several other functions, using a polymorphic dispatch instead of a "when" structure, doing something in this spirit ?:

fun dispatch<Float>() = println("I'm a Float")
fun dispatch<String>() = println("I'm a String")

Furthermore, what is the performance cost of such "when" statement ? Let's say I call dispatch<String>() : the "when" can be resolved at compile time. Will a clever compiler see that and just replace it with println("I'm a String"), or will there be a performance overhead ?

CodePudding user response:

Is there a way to break it into several other functions, using a polymorphic dispatch instead of a "when" structure, doing something in this spirit ?:

No. There's no way to do that for this function.

There are occasionally ways to do similar things, but you generally at least need a T or Foo<T> to make that work.

CodePudding user response:

If you do not need the possibility to call dispatch with some reified type parameter from another inline function, you could replace the when block with extensions of the different class's companion objects:

fun String.Companion.dispatch() = println("I'm a String")
fun Float.Companion.dispatch() = println("I'm a Float")

Then it's not dispatch<String>() but String.dispatch(), and you got rid of the when.

  • Related