1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Kotlin】ByteArrayを無限に連結したい

Last updated at Posted at 2021-10-28

やりたいこと

【Java】Byte配列を無限に連結したい
のKotlin版。ByteArrayを無限に連結できる1つの関数が欲しい。

追記

コメントいただきましたがreduceであっさりできますね。ありがとうございます。

fun concatArrays(vararg arrays: ByteArray): ByteArray =
    arrays.reduce { acc, cur -> acc + cur }

結果

可変長引数で順にPlusすることでひとまず実現。Kotlinの可変長引数はArrayに格納されているため下記では
arraysArray<ByteArray>となる。もっとスマートな方法もありそう。

fun concatArrays(vararg arrays: ByteArray): ByteArray{
  var result = byteArrayOf()
  arrays.forEach { array ->
      result += array
  }
  return result
}

fun main(args: Array<String>) {
  val v1 = byteArrayOf(1, 2)
  val v2 = byteArrayOf(3, 4, 5)
  val v3 = byteArrayOf(6, 7, 8, 9)
  
  println(Arrays.toString(concatArrays(v1)))
  println(Arrays.toString(concatArrays(v1, v2)))
  println(Arrays.toString(concatArrays(v1, v2, v3)))
}

Output

[1, 2]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?