kotlin内联函数调用vs函数与默认类型参数调用

发布于 2025-02-12 06:25:02 字数 397 浏览 3 评论 0原文

考虑以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

生生不灭 2025-02-19 06:25:03

每当我们调用函数并且都有多个匹配的多个过载时,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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文