kotlin - 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) }
}
}
解决方案
如果默认参数在没有默认值的参数之前,则只能通过使用命名参数调用函数来使用默认值。
例子:
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
推荐阅读
- python - 由于读取双斜杠而不是 Python 中的一个斜杠,登录失败
- javascript - 在catch子句中声明e变量的正确方法是什么
- python - Javascript 函数未定义:Python Selenium
- flutter - 我可以用颤振相机包制作流吗?
- python - Python 抓取表格的所有列,但我只想查看其中一列
- python - 如果我之前对函数的列表参数进行切片,为什么切片分配只能就地工作?
- neo4j - 图形的密码查询
- tensorflow - ValueError:数据基数不明确:请提供具有相同第一个维度的数据。训练多输入 CNN 时
- javascript - 反应 onClientClick 没有触发我的函数处理程序
- vb.net - 我需要将代码转换为 VB.net。隐藏 Selenium 以防止使用 firefoxdriver 检测站点