aus*_*ser 3 default-parameters kotlin
有谁知道为什么调用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) }
}
}
Run Code Online (Sandbox Code Playgroud)
如果默认参数位于没有默认值的参数之前,则只能通过调用带有命名参数的函数来使用默认值。
例子:
fun foo(bar: Int = 0, baz: Int) { ... }
foo(baz = 1) // The default value bar = 0 is used
Run Code Online (Sandbox Code Playgroud)
在您的示例中,这将起作用:
x.method1(argQ = 1) { res: Int -> println(res) } // The default value argStr = "" is used
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1106 次 |
| 最近记录: |