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")
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值