Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to convert a List to a Pair in Kotlin

Tags:

kotlin

There is an idiomatic approach to converting a Pair into a List:

Pair(a, b).toList()

No I am searching for the opposite process. My best approach looks like this:

Pair(list[0], list[1])

My problem with this is that I need to make a List value in code first for this to work. I would love something like this:

listOf(a, b).toPair()
like image 892
creativecreatorormaybenot Avatar asked Mar 27 '18 16:03

creativecreatorormaybenot


Video Answer


2 Answers

For a more general solution you could use the extension function zipWithNext* which

Returns a list of pairs of each two adjacent elements in this collection.

The example in the documentation explains it better:

val letters = ('a'..'f').toList()
val pairs = letters.zipWithNext()

println(letters) // [a, b, c, d, e, f]
println(pairs) // [(a, b), (b, c), (c, d), (d, e), (e, f)]

*note that this function is available since v1.2 of Kotlin.

like image 126
stan0 Avatar answered Sep 19 '22 18:09

stan0


You can make this extension for yourself:

fun <T> List<T>.toPair(): Pair<T, T> {
    if (this.size != 2) {
        throw IllegalArgumentException("List is not of length 2!")
    }
    return Pair(this[0], this[1])
}

The error handling is up to you, you could also return a Pair<T, T>? with null being returned in the case where the List is not the correct length. You could also only check that it has at least 2 elements, and not require it to have exactly 2.

Usage is as you've described:

listOf(a, b).toPair()
like image 30
zsmb13 Avatar answered Sep 19 '22 18:09

zsmb13