2
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】listOfNulls的なこと(null埋めしたList取得)をする

Posted at

やりたかったこと

KotlinにはnullArrayを初期化するarrayOfNulls関数が用意されています。

val nullArray: Array<Any?> = arrayOfNulls(size)

Listでも同様にlistOfNulls関数が用意されているかと思いましたが、有りませんでした。

代替手段

以下のように書くことでnull埋めしたListを取得できます。

val nullList: List<Any?> = List(size) { null }

補足

Listのコンストラクタ的なものを呼んでいますが、これは実際は以下のように定義されています。
使う感じはKotlinArrayのコスントラクタと同じですね。

/**
 * 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)
2
1
2

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
2
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?