Variable number of arguments (Varargs)

时间:2023-03-10 07:11:02
Variable number of arguments (Varargs)

A parameter of a function (normally the last one) may be marked with vararg modifier:

    fun <T> asList(vararg ts: T): List<T> {
val result = ArrayList<T>()
for (t in ts) // ts is an Array
result.add(t)
return result
}

allowing a variable number of arguments to be passed to the function:

val list = asList(1, 2, 3)
Inside a function a vararg-parameter of type T is visible as an array of T, i.e. the ts variable in the example above has type Array<out T>.

Only one parameter may be marked as vararg. If a vararg parameter is not the last one in the list, values for the following parameters can be passed using the named argument syntax, or, if the parameter has a function type, by passing a lambda outside parentheses.

When we call a vararg-function, we can pass arguments one-by-one, e.g. asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *):

val a = arrayOf(1, 2, 3)
val list = asList(-1, 0, *a, 4)

1.一般是函数中的最后一个参数

2.在一个函数中只可以声明一个参数为vararg
3.如果可变参数不是函数中的最后一个参数,则后面的参数通过命名参数语法来传递参数值
4.如果参数类型是函数, 可以在括号之外传递一个
5.传递一个已有的数组则通过*号

    @Test fun testPair() {
val list = listOf("hello", true, "world")
val array = list.toTypedArray()
printVararg(*array, lastPrams = "...list...")
} fun printVararg(vararg params: Any, lastPrams: String) {
for (param in params) {
println("param : $param, lastPrams: $lastPrams")
}
}