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()
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With