syntax - Kotlin 中的变量名或扩展运算符之前的 Kotlin 星号运算符

我想知道 Kotlin 中变量名前的星号到底是做什么的。 我在 Spring boot Kotlin example 中看到了这个 (*args) :

@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 运算符

来自 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 的函数之前应用于数组。

例如...

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

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

使用扩展运算符将数组元素作为参数传递:

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

注意事项:

  • * 运算符也是乘法运算符(当然)。
  • 该运算符只能在将参数传递给函数时使用。操作的结果无法存储,因为它没有产生任何值(value)(它纯粹是语法糖)。
  • 操作符一开始可能会让一些 C/C++ 程序员感到困惑,因为它看起来像是在取消引用指针。不是; Kotlin 没有指针的概念
  • 在调用可变参数函数时,该运算符可以在其他参数之间使用。这在示例 here 中得到了演示。 .
  • 运算符类似于各种函数式编程语言中的apply函数。

https://stackoverflow.com/questions/39389003/

相关文章:

kotlin - 我们何时应该在 Kotlin 上使用 run、let、apply、also 和 w

string - Kotlin - 如何正确连接字符串

android-studio - 用于使用 gradle (1.1.2-5) 构建的 kotlin

generics - Kotlin 泛型中 "*"和 "Any"之间的区别

intellij-idea - IntelliJ 中的 Kotlin Unresolved refe

unit-testing - 如何在 Kotlin 中管理单元测试资源,例如启动/停止数据库连接或嵌

list - Kotlin:如何使用列表强制转换:未经检查的强制转换:kotlin.collecti

java - Kotlin:等效于 KClass 的 getClass()

kotlin - 覆盖 Kotlin 数据类的 getter

generics - 通用扩展类 AND 在 Kotlin 中实现接口(interface)