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 Operator号操作员.

Kotlin Reference...

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的函数之前,可以将其应用于array.

For Example...

如果你有一个函数可以接受不同数量的参数...

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:

  • *号操作员当然也是multiplication operator号操作员.
  • 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.
  • 该运算符类似于各种函数式编程语言中的apply函数.

Kotlin相关问答推荐

为什么";";.equals(1)在柯特林语中是有效的,但";";=1是无效的?

如何在Docker中使用Selenium和chromedriver?

Kotlin - 什么时候和什么时候不喜欢内联函数,为什么?

Kotlin 中命名构造函数的惯用方式

Kotlin - 如何避免在密封类的 when() 语句中转换第二个变量

返回 kotlin 中的标签和 lambda 表达式

在 Kotlin 中,如何绑定扩展方法以在接收器范围函数中工作

在 Kotlin 协程中切换 IO 和 UI 的正确方法是什么?

Jetpack Compose:当状态从另一个活动改变时强制重组

为什么 Kotlin 在 sumOf 函数 lambda 中默认不将数字视为Int?

如何限制 Kotlin 中的枚举?

如何使用 Either monad 并避免嵌套 flatMap

OnClickListener 未在 ConstraintLayout 上触发

如何有效地填充 Gradle Kotlin DSL 中的额外属性?

将 Gradle 子元素与 Kotlin 多平台一起使用

无法解决:androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1

如何将vararg作为数组传递给Kotlin中的函数?

在 kotlin 中,如何将主构造函数中的属性设置器设为私有?

使用 java lambda 调用 kotlin 函数时,Kotlin 无法访问 kotlin.jvm.functions.Function1

Kotlin反射不可用