I’m not sure if this is a bug in the compiler or if I’m missing something obvious. This function compiles just fine:
inline fun <reified S> getParserForType() : (String)->S? {
val valueParser : ((String) -> S?)? = when (S::class) {
Float::class -> {s:String->s.toFloatOrNull() as S?}
Double::class -> {s:String->s.toDoubleOrNull() as S?}
else -> null
}
if( valueParser==null ) throw IllegalArgumentException()
return valueParser
}
However, if I use the IDE suggestion to refactor to use the Elvis operator, as follows…
inline fun <reified S> getParserForType() : (String)->S? {
val valueParser : (String) -> S? = when (S::class) {
Float::class -> {s:String->s.toFloatOrNull() as S?}
Double::class -> {s:String->s.toDoubleOrNull() as S?}
else -> null
} ?: throw IllegalArgumentException()
return valueParser
}
…I get two compile errors:
Error:(47, 25) Kotlin: Type mismatch: inferred type is (String) -> S? but Nothing? was expected
Error:(48, 26) Kotlin: Type mismatch: inferred type is (String) -> S? but Nothing? was expected
Am I missing something or is this a compiler bug?
On a related note… is there any more idiomatic way to check the type of a reified type parameter? Comparing it to the appropriate ::class seems to be the only way. Am I missing something?