kotlin内联函数调用vs函数与默认类型参数调用
考虑以下代码:
fun foo(type: Class<out Any> = Any::class.java) {
}
inline fun <reified T : Any> foo() {
}
fun main() {
foo() // ERROR!
}
此代码导致以下错误:
类型推理失败:没有足够的信息来推断参数 t inline fun foo():单位
请明确指定。
默认参数为什么不默认编译器默认为非插入函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每当我们调用函数并且都有多个匹配的多个过载时,Kotlin都会更喜欢它认为是最具体的过载。例如,它比更多的通用类型(Supertypes)更喜欢接收更具体的参数类型(亚型)的函数。
同样,如果编译器必须用默认值替换缺少的参数,则它将其视为不太确切的匹配。它更喜欢候选人,其中我们完全使用函数定义中的参数。这在文档中描述了:
https://kotlinlang.org/spec/spec/spec/overload-resolution.html
对于函数是否被内衬,是否使用repied参数或类型参数未知。
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:
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.