简体   繁体   中英

entering a list as a function's default value in kotlin

I defined the function "fireAtTarget" in kotlin. 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

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:

fun foo(value: List<Int>=listOf(1,2)) { }

The problem was solved by inserting whitespace space before the 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.

See: https://kotlinlang.org/docs/reference/operator-overloading.html#comparison

您可以创建一个具有默认值的列表,如下所示:

val defaultValueList = List<String>(10) {"I am default"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM