Home > Blockchain >  What is the function of the * operation in Kotlin?
What is the function of the * operation in Kotlin?

Time:12-06

The Code A is from the offical sample enter image description here

CodePudding user response:

From the documentation of varargs:

When you call a vararg -function, you can pass arguments individually, for example asList(1, 2, 3). If you already have an array and want to pass its contents to the function, use the spread operator (prefix the array with *):

val a = arrayOf(1, 2, 3)
val list = asList(-1, 0, *a, 4)

As you see, it expands an array to multiple values for use in a vararg. If you havd an array containing the elements 1, 2, 3, you can pass *yourArray to a method that is equivalent to yourMethod(1,2,3).

CodePudding user response:

In Kotlin * is the Spread Operator. From docs :

When you call a vararg -function, you can pass arguments individually, for example asList(1, 2, 3). If you already have an array and want to pass its contents to the function, use the spread operator (prefix the array with *):

val a = arrayOf(1, 2, 3)
val list = asList(-1, 0, *a, 4)

In this case tasks will contain the list of strings from R.array.tasks

  • Related