From 5db75c993bf98ee1f1d713544963ec67ff3367f9 Mon Sep 17 00:00:00 2001 From: Ilya Gorbunov Date: Mon, 26 Dec 2016 22:20:53 +0300 Subject: [PATCH] Introduce array-like list instantiation functions. #KT-14935 Fixed --- .../src/kotlin/collections/Collections.kt | 20 +++++++++++++++++++ .../stdlib/test/collections/CollectionTest.kt | 6 ++++++ 2 files changed, 26 insertions(+) diff --git a/libraries/stdlib/src/kotlin/collections/Collections.kt b/libraries/stdlib/src/kotlin/collections/Collections.kt index 6c20db08d5a..96cb57725e4 100644 --- a/libraries/stdlib/src/kotlin/collections/Collections.kt +++ b/libraries/stdlib/src/kotlin/collections/Collections.kt @@ -104,6 +104,26 @@ public fun listOfNotNull(element: T?): List = if (element != null) /** Returns a new read-only list only of those given elements, that are not null. The returned list is serializable (JVM). */ public fun listOfNotNull(vararg elements: T?): List = elements.filterNotNull() +/** + * Creates a new read-only list with the specified [size], where each element is calculated by calling the specified + * [init] function. The [init] function returns a list element given its index. + */ +@SinceKotlin("1.1") +@kotlin.internal.InlineOnly +public inline fun List(size: Int, init: (index: Int) -> T): List = MutableList(size, init) + +/** + * Creates a new mutable list with the specified [size], where each element is calculated by calling the specified + * [init] function. The [init] function returns a list element given its index. + */ +@SinceKotlin("1.1") +@kotlin.internal.InlineOnly +public inline fun MutableList(size: Int, init: (index: Int) -> T): MutableList { + val list = ArrayList(size) + repeat(size) { index -> list.add(init(index)) } + return list +} + /** * Returns an [IntRange] of the valid indices for this collection. */ diff --git a/libraries/stdlib/test/collections/CollectionTest.kt b/libraries/stdlib/test/collections/CollectionTest.kt index 6f301a2d966..8bce7f3ed5b 100644 --- a/libraries/stdlib/test/collections/CollectionTest.kt +++ b/libraries/stdlib/test/collections/CollectionTest.kt @@ -24,6 +24,12 @@ import kotlin.comparisons.* class CollectionTest { + @Test fun createListWithInit() { + val list = List(3) { index -> "x".repeat(index + 1) } + assertEquals(3, list.size) + assertEquals(listOf("x", "xx", "xxx"), list) + } + @Test fun joinTo() { val data = listOf("foo", "bar") val buffer = StringBuilder()