やりたかったこと
Kotlin
にはnull
でArray
を初期化するarrayOfNulls
関数が用意されています。
val nullArray: Array<Any?> = arrayOfNulls(size)
List
でも同様にlistOfNulls
関数が用意されているかと思いましたが、有りませんでした。
代替手段
以下のように書くことでnull
埋めしたList
を取得できます。
val nullList: List<Any?> = List(size) { null }
補足
List
のコンストラクタ的なものを呼んでいますが、これは実際は以下のように定義されています。
使う感じはKotlin
のArray
のコスントラクタと同じですね。
/**
* Creates a new read-only list with the specified [size], where each element is calculated by calling the specified
* [init] function.
*
* The function [init] is called for each list element sequentially starting from the first one.
* It should return the value for a list element given its index.
*
* @sample samples.collections.Collections.Lists.readOnlyListFromInitializer
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T> = MutableList(size, init)