我想知道 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'
注意事项:
*
运算符也是乘法运算符(当然)。apply
函数。https://stackoverflow.com/questions/39389003/
相关文章:
kotlin - 我们何时应该在 Kotlin 上使用 run、let、apply、also 和 w
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()