gpt4 book ai didi

Kotlin 默认参数排序

转载 作者:行者123 更新时间:2023-12-02 13:20:41 30 4
gpt4 key购买 nike

有谁知道为什么调用 method1 不编译而调用 method2 编译?

class MyApp {

interface X {

fun <Q : Any, A : Any> method1(argStr: String = "", argQ: Q, argH: (A) -> Unit)

fun <Q : Any, A : Any> method2(argQ: Q, argStr: String = "", argH: (A) -> Unit)
}

fun test(x: X) {

/* Call to method1 does not work - the following errors are produced
* Error: Kotlin: Type inference failed:
* fun <Q : Any, A : Any> method1(argStr: String = ..., argQ: Q, argH: (A) -> Unit): Unit
* cannot be applied to (Int,(Int) -> Unit)
* Error: Kotlin: The integer literal does not conform to the expected type String
* Error: Kotlin: No value passed for parameter 'argQ'
*/

x.method1(1) { res: Int -> println(res) }

/* No errors here */
x.method2(1) { res: Int -> println(res) }
}

}

最佳答案

如果默认参数在没有默认值的参数之前,只能通过调用带有命名参数的函数来使用默认值

示例:

fun foo(bar: Int = 0, baz: Int) { ... }

foo(baz = 1) // The default value bar = 0 is used

在您的示例中,这将起作用:

x.method1(argQ = 1) { res: Int -> println(res) } // The default value argStr = "" is used

Further reading

关于Kotlin 默认参数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56733865/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com