Kotlin asterisk operator before variable name or Spread Operator in Kotlin

后端 未结 5 712
猫巷女王i
猫巷女王i 2020-11-30 00:59

I want to know what exactly an asterisk does before a variable name in Kotlin. I saw this (*args) in a Spring boot Kotlin example:

@SpringBootApp         


        
5条回答
  •  Happy的楠姐
    2020-11-30 01:20

    If a function which accept a vararg(Variable number of arguments) parameter like:

    fun sum(vararg data:Int)
    {
       // function body here         
    }
    

    Now to call this method, we can do:

    sum(1,2,3,4,5)
    

    But what if we have these value in an array, like:

    val array= intArrayOf(1,2,3,4,5)
    

    then, to call this method we have to use spread operator, like:

     sum(*array)
    

    Here, *(spread operator) will pass all content of that array.

    *array is equivalent to 1,2,3,4,5

    But wait a minute, what if we call it like this: sum(array) it will give us Type Mismatch compile time error:

    Type mismatch.
    Required:Int
    Found:IntArray
    

    The problem is sum function accept a vararg Int parameter(which accept value like: 1,2,3,4,5) and if we pass array, it will be passed as IntArray.

提交回复
热议问题