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:ide

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.spa

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 *):code

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

 1.通常是函數中的最後一個參數orm

2.在一個函數中只能夠聲明一個參數爲vararg
3.若是可變參數不是函數中的最後一個參數,則後面的參數經過命名參數語法來傳遞參數值
4.若是參數類型是函數, 能夠在括號以外傳遞一個
5.傳遞一個已有的數組則經過*號
blog

    @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")
        }
    }
相關文章
相關標籤/搜索