0

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?

2
  • You have the answer right in the error message: Please specify it explicitly. An example would be: foo<String>() or _foo<SomeClassOfYours>() Commented Jul 2, 2022 at 11:38
  • @lukas.j That's my point though. If you remove the inlined function, then the code works because it just uses the non-inlined function with a default argument. I want to know why the compiler isn't sophisticated enough to call the non-inlined function in the event that an explicit type argument isn't provided. Commented Jul 2, 2022 at 11:40

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.