Kotlin 变量名前的 Kotlin 星号运算符或扩展运算符 [英] Kotlin asterisk operator before variable name or Spread Operator in Kotlin
问题描述
我想知道 Kotlin 中在变量名之前星号的作用.我在 *args)="noreferrer">Spring Boot Kotlin 示例:
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:
@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)
}
推荐答案
*
运算符在 Kotlin 中被称为 Spread 运算符.
The *
operator is known as the Spread Operator in Kotlin.
来自 Kotlin 参考...
当我们调用一个可变参数函数时,我们可以一个一个地传递参数,例如asList(1, 2, 3),或者,如果我们已经有一个数组并且想要将它的内容传递给函数,我们使用扩展运算符(在数组前加上 *):
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 *):
它可以在将数组传递给接受 varargs
的函数之前应用于数组.
It can be applied to an Array before passing it into a function that accepts varargs
.
如果你有一个接受不同数量参数的函数......
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'
注意事项:
*
运算符也是 乘法运算符(当然).- 该运算符只能在向函数传递参数时使用.操作的结果无法存储,因为它不产生任何价值(它纯粹语法糖).
- 该运算符一开始可能会让一些 C/C++ 程序员感到困惑,因为它看起来像是正在取消引用指针.它不是;Kotlin 没有指针的概念.
- 在调用可变参数函数时,该运算符可以在其他参数之间使用.这在此处的示例中进行了演示.
- 该运算符类似于各种函数式编程语言中的
apply
函数.
- 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.
这篇关于Kotlin 变量名前的 Kotlin 星号运算符或扩展运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!