LoginSignup
9
4

More than 5 years have passed since last update.

配列を展開して可変長引数に引き渡す

Posted at

メモがてら。リストの先頭に何か足したリストを生成するのを、いみゅーたぶるにどうしたら良いのかな、
listOfに配列を展開して渡せるものだろうか、と思っていたら、

さらりと spread operator って書いてあった。

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 *):

val a = arrayOf(1, 2, 3)
val list = asList(-1, 0, *a, 4)

Functions - Kotlin Programming Language

コンスタラクタで受け取った可変長引数のリストの先頭に固定のprefixを足したくて探したのだけど、

class Sample(vararg components: String) {
  private val PREFIX = "prefix"
  private val components = listOf(PREFIX, *components)
}

で、いけた。なるほど。

9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4