Kotlin 1.3.70 - Notable Library Additions
Mar 17, 2020
2 minute read

Kotlin 1.3.70 added some useful experimental library functions. To use them one needs to apply an @ExperimentalStdlibApi annotation.

Following sections list my favorite additions.

Scan functions on Iterable and Sequence

Similar to reduce, scan allows computing intermediate results on a collection.

@Test
fun `scan function`() {
    val intermediateSums = sequenceOf(1, 2, 3, 4, 5)
        .scan(0) { acc, next -> acc + next }
        .toList()

    expect(intermediateSums).contains(1, 3, 6, 10, 15)
}

Collections builders

Builders provide a concise way to create and populate a collection without creating to many intermediate collections or merging different ones. I guess we will see more usages of mapTo and filterTo.

@Test
fun `build list`() {
    val result = buildList(5) {
        add(1)
        listOf(2, 3, 4).mapTo(this) { it }
        add(0, 0)
    }

    expect(result).containsExactly(0, 1, 2, 3, 4)
}

@Test
@Suppress("RemoveExplicitTypeArguments")
fun `build map`() {
    val map = buildMap<Int, Int> { // type inference bug!
        put(1, 1)
    }

    expect(map).contains(1 to 1)
}

Array Deque implementation

Multiplatform projects will like the addition of a Queue implementation. Kotlin-JVM may still prefer java.util.ArrayDeque.

@Test
fun `array deque`() {
    val deck = ArrayDeque<Int>()
    deck.addFirst(1)
    deck.add(2)
    deck.addLast(0)

    expect(deck).containsExactly(1, 2, 0)
    expect(deck).get(0).toBe(1)

    deck.removeFirst()
    deck.removeLast()

    expect(deck).toBe(ArrayDeque<Int>().apply { add(2) })
}

XXXOrNull additions

@Test
fun `reduce or null`() {
    expect(sequenceOf<Int>().reduceOrNull { acc, next -> acc + next }).toBe(null)
    expect(listOf(1).reduceOrNull { acc, next -> acc + next }).toBe(1)
}

@Test
fun `random or null`() {
    expect(listOf<Int>().randomOrNull()).toBe(null)
}