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")
            }
        }
  • 相关阅读:
    dede图片横向滚动
    dede各种运用[转]
    PROFIBUS-DP现场总线的结构及应用
    51单片机的中断优先级及中断嵌套
    WPF里面制作圆角文本框
    【转】什么叫51单片机最小系统
    【转】(C#)OPC客户端源码
    路漫漫其修远兮,吾要上下左右前后而求索
    二叉树创建为什么用二级指针
    无向图的邻接表创建
  • 原文地址:https://www.cnblogs.com/liulipeng/p/7406634.html
Copyright © 2011-2022 走看看