[英]entering a list as a function's default value in kotlin
I defined the function "fireAtTarget" in kotlin.我在 kotlin 中定义了函数“fireAtTarget”。 As an argument, I need to insert a default value for the list.
作为参数,我需要为列表插入一个默认值。 How could I achieve this?
我怎么能做到这一点?
fun fireAtTarget(massKg: Double=80.2, eachGunAmmo: List<Int>=listOf(2, 3): Boolean{
//function body
}
I expect to call fireAtTarget() with no arguments getting 0 error messages我希望在没有参数的情况下调用 fireAtTarget() 得到 0 错误消息
There is a syntax error in your code: you simply forgot to close bracket in function parameters declaration:您的代码中存在语法错误:您只是忘记在函数参数声明中关闭括号:
fun fireAtTarget(massKg: Double=80.2, eachGunAmmo: List<Int> = listOf(2,3)): Boolean {
//function body
}
I was experiencing this problem (IntelliJ reports an error Expecting a top level declaration
) with the following code:我遇到了这个问题(IntelliJ 报告错误
Expecting a top level declaration
),代码如下:
fun foo(value: List<Int>=listOf(1,2)) { }
The problem was solved by inserting whitespace space before the equals List<Int>*space*=listOf
通过在 equals
List<Int>*space*=listOf
之前插入空格解决了问题
fun foo(value: List<Int> = listOf(1,2)) { }
The Kotlin language has a >=
operator that the original may be confused with. Kotlin 语言有一个
>=
操作符,可能与原文混淆。
See: https://kotlinlang.org/docs/reference/operator-overloading.html#comparison请参阅: https : //kotlinlang.org/docs/reference/operator-overloading.html#comparison
您可以创建一个具有默认值的列表,如下所示:
val defaultValueList = List<String>(10) {"I am default"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.