变量名前的Kotlin星号运算符或Kotlin中的Spread运算符 [英] Kotlin asterisk operator before variable name or Spread Operator in Kotlin

查看:407
本文介绍了变量名前的Kotlin星号运算符或Kotlin中的Spread运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Kotlin中,变量名之前星号到底是做什么的. 我在*args)"rel =" noreferrer> Spring boot Kotlin示例:

I want to know what exactly asterisk does before variable name in Kotlin. I saw this (*args) at 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.

来自科林参考书.

当我们调用vararg函数时,我们可以一个一个地传递参数,例如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()
}

您可以像这样将数组传递给它...

You can pass an array into it like so...

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


注释:

  • *运算符也是乘法运算符(当然).
  • 仅当将参数传递给函数时才能使用运算符. 操作的结果无法存储,因为它不产生任何值(它是语法糖).
  • 运算符起初可能会使某些C/C ++程序员感到困惑,因为它看起来像是在取消引用指针.不是Kotlin 没有指针的概念.
  • 在调用vararg函数时,可以在其他参数之间使用运算符.在示例此处中进行了演示.
  • 运算符类似于各种功能编程语言中的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中的Spread运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆