Kotlin asterisk operator before the name of a variable or Spread operator in Kotlin

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

@SpringBootApplication
open class Application {

    @Bean
    open fun init(repository: CustomerRepository) = CommandLineRunner {
        repository.save(Customer("Jack", "Bauer"))
        repository.save(Customer("Chloe", "O'Brian"))
        repository.save(Customer("Kim", "Bauer"))
        repository.save(Customer("David", "Palmer"))
        repository.save(Customer("Michelle", "Dessler"))
    }
}

fun main(args: Array<String>) {
    SpringApplication.run(Application::class.java, *args)
}
+77
source share
5 answers

The operator *is known as the distribution operator in Kotlin.

From Kotlin Reference ...

When we call the vararg function, we can pass the arguments one by one, for example, asList (1, 2, 3) or, if we already have an array and we want to pass its contents to the function, we use the distribution operator (array prefix *) :

, varargs.

...

, ...

fun sumOfNumbers(vararg numbers: Int): Int {
    return numbers.sum()
}

...

val numbers = intArrayOf(2, 3, 4)
val sum = sumOfNumbers(*numbers)
println(sum) // Prints '9'

:

  • * ().
  • . , ( ).
  • C/C++, , . ; .
  • vararg. .
  • apply .
+125

, " !?!", , List , vararg. :

someFunc(x, y, *myList.toTypedArray())

, someFunc vararg , .

+19

, :

vararg-, , . asList (1, 2, 3), , , ( *):

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

Java , * , spread . Java .

+2

, vararg ( ), :

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

, , :

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

, , :

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

then, to call this method, we must use the distribution operator, for example:

 sum(*array)

Here * (distribution operator) will skip the entire contents of this array.

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

But wait a minute, if we call it this: sum(array) it will give us a type mismatch error:

Type mismatch.
Required:Int
Found:IntArray

The problem is that the function sumtakes a parameter vararg Int(which takes a value, for example: 1,2,3,4,5), and if we pass an array, it will be passed as IntArray.

+2
source

Source: https://habr.com/ru/post/1693806/


All Articles