zoukankan      html  css  js  c++  java
  • 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")
            }
        }
  • 相关阅读:
    代码控制数据流量开关
    用wifi来调试应用程序
    详细解读LruCache类
    修改博客园默认的代码字体大小
    通过Gson解析Json数据
    Docker、Kubernetes的 CICD实现思路
    React中路由传参及接收参数的方式
    微信小程序开发工具调试没问题,真机调试Provisional headers are shown
    物联网卡三码
    【微信开发】-- 企业转账到用户
  • 原文地址:https://www.cnblogs.com/liulipeng/p/7406634.html
Copyright © 2011-2022 走看看