When the compiler applies type erasure, the return type will be determined. So, let's say you use String ... your method will look like this:
fun something(type: Type<String>): String = when (type) { is StringType -> "Happy Halloween!" is IntType1 -> 42
This thing: you must know your return type at compile time . If you do not know this, you should report this to the compiler:
fun <T> something(type: Type<T>): Any = when (type) { is StringType -> "blabla" is IntType1 -> 42 is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b else -> throw IllegalArgumentException() }
Sorry this code, it's not that you are jumping, you are going to throw after the method returns ...
But you can do it:
fun <T> something(type: Type<T>): T = when (type) { is StringType -> type.b //is IntType1 -> 42 remove this! is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b else -> throw IllegalArgumentException() }
Assuming type.a and type.b are parameterized as T. Then your code will work fine.
source share