Kotlinで変数名の前にアスタリスクを付けると、具体的に何をするのか知りたいです。この(*args
)は、Spring Boot Kotlin の例:
@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)
}
ベストアンサー1
オペレーター*
はスプレッド演算子Kotlin で。
From the Kotlin Reference:
When you call a
vararg
-function, you can pass arguments individually, for exampleasList(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*
):
It can be applied to an Array before passing it into a function that accepts vararg
.
For Example...
If you have a function that accepts a varied number of arguments...
fun sumOfNumbers(vararg numbers: Int): Int {
return numbers.sum()
}
Use the spread operator to pass an array's elements as the arguments:
val numbers = intArrayOf(2, 3, 4)
val sum = sumOfNumbers(*numbers)
println(sum) // Prints '9'
Notes:
- The
*
operator is also the multiplication operator (of course). - The operator can only be used when passing arguments to a function. The result of the operation cannot be stored since it yields no value (it is purely syntactic sugar).
- The operator may confuse some C/C++ programmers at first because it looks like a pointer is being de-referenced. It isn't; Kotlin has no notion of pointers.
- The operator can be used in-between other arguments when calling a
vararg
-function. This is demonstrated in the example here. - The operator is similar to the
apply
function in various functional programming languages.