Introduce array-like list instantiation functions.
#KT-14935 Fixed
This commit is contained in:
@@ -104,6 +104,26 @@ public fun <T : Any> listOfNotNull(element: T?): List<T> = if (element != null)
|
|||||||
/** Returns a new read-only list only of those given elements, that are not null. The returned list is serializable (JVM). */
|
/** Returns a new read-only list only of those given elements, that are not null. The returned list is serializable (JVM). */
|
||||||
public fun <T : Any> listOfNotNull(vararg elements: T?): List<T> = elements.filterNotNull()
|
public fun <T : Any> listOfNotNull(vararg elements: T?): List<T> = 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 <T> List(size: Int, init: (index: Int) -> T): List<T> = 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 <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T> {
|
||||||
|
val list = ArrayList<T>(size)
|
||||||
|
repeat(size) { index -> list.add(init(index)) }
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns an [IntRange] of the valid indices for this collection.
|
* Returns an [IntRange] of the valid indices for this collection.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -24,6 +24,12 @@ import kotlin.comparisons.*
|
|||||||
|
|
||||||
class CollectionTest {
|
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() {
|
@Test fun joinTo() {
|
||||||
val data = listOf("foo", "bar")
|
val data = listOf("foo", "bar")
|
||||||
val buffer = StringBuilder()
|
val buffer = StringBuilder()
|
||||||
|
|||||||
Reference in New Issue
Block a user