Home > Blockchain >  Kotlin inline function call vs function call with default type argument
Kotlin inline function call vs function call with default type argument

Time:07-03

Consider the following code:

fun foo(type: Class<out Any> = Any::class.java) {

}

inline fun <reified T : Any> foo() {

}

fun main() {
    foo() // ERROR!
}

This code causes the following error:

Type inference failed: Not enough information to infer parameter T in inline fun foo(): Unit

Please specify it explicitly.

Why doesn't the compiler just default to the non-inlined function, with a default argument?

CodePudding user response:

Whenever we call a function and there are multiple overloads that all match, Kotlin prefers the overload that it considers to be the most specific. For example, it prefers a function receiving a more specific argument types (subtypes) than more generic types (supertypes).

Similarly, if the compiler has to substitute missing arguments with defaults, it considers it a less exact match. It prefers the candidate where we used arguments exactly as in the function definition. This is described in the documentation:

For each candidate we count the number of default parameters not specified in the call (i.e., the number of parameters for which we use the default value). The candidate with the least number of non-specified default parameters is a more specific candidate;

https://kotlinlang.org/spec/overload-resolution.html

It doesn't matter if functions are inlined or not, if they use reified parameters or if the type parameter is unknown.

  • Related