Idiomatic way to convert a List to a Pair in Kotlin
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()
Here's a variation on @zsmb13's solution that avoids creating the exception explicitly and dereferencing the list by index:
fun <T> List<T>.toPair(): Pair<T, T> {
require (this.size == 2) { "List is not of length 2!" }
val (a, b) = this
return Pair(a, b)
}