Youssef Shoaib [MOD]
07/13/2022, 10:33 PM@OverloadResolutionByLambdaReturnType
not cover the case where one of the return types is a subtype of the other? For instance, this surprisingly fails (playground):
@OptIn(kotlin.experimental.ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
inline fun printIf(condition: Boolean, message: () -> Any?) {
if(condition) println(message())
}
inline fun printIf(condition: Boolean, message: () -> Int) {
if(condition) println(message())
}
fun main() {
printIf(true) { 42 }
printIf(false) { "hello world" } // Type mismatch: inferred type is String but Int was expected
}
This can obv be used to avoid boxing primitives like Int when unneeded. I know the cost of boxing is marginal, but in a tight loop it can be detrimental.