• 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")
            }
        }
  • 相关阅读:
    HDU5732 Subway【树重心 树哈希】
    HDU6311 Cover【欧拉路径 | 回路】
    HDU6370 Werewolf 【基环内向树】
    HDU6321 Dynamic Graph Matching【状压DP 子集枚举】
    HDU6331 Problem M. Walking Plan【Floyd + 矩阵 + 分块】
    HDU6403 Card Game【基环树 + 树形DP】
    HDU5691 Sitting in Line【状压DP】
    Codeforces Round #650 (Div. 3)
    2017-2018 ACM-ICPC, NEERC, Northern Subregional Contest
    Codeforces Round #649 (Div. 2)
  • 原文地址:https://www.cnblogs.com/liulipeng/p/7406634.html
Copyright © 2020-2023  润新知