Skip to Content

Kotlin Tuples and Extension Properties

Scala-like Pair and Tuple in Kotlin

Posted on

One of the things that has taken me a bit of time to get used to in Kotlin is the lack of Scala-like syntax for accessing values in Pair and Triple.

In Scala, you can refer to values in tuples by their position number, rather than words.

// Scala

val pair: (Int, String) = (1, "A")
println(pair._1)  // 1
println(pair._2)  // "A"
  
val triple: (Int, String, Boolean) = (1, "A", true)
println(triple._1)  // 1
println(triple._2)  // "A"
println(triple._3)  // true

Let’s use one of my favorite Kotlin features - extension properties , to make this look more like Scala!

// Kotlin

// Define our extension properties for first (_1) and second (_2)
val <A,B> Pair<A,B>._1: A get() = this.first
val <A,B> Pair<A,B>._2: B get() = this.second

// Define the Pair and use our new properties
val pair = 1 to "A"
println(pair._1)  // 1
println(pair._2)  // "A"

In the code above, we define two new extensions to Kotlin’s Pair class, which allow us to refer to first as _1 and second as _2. Since Kotlin also has a Triple, we should go ahead and write extensions for that too.

// Kotlin

// Define our extension properties
val <A,B,C> Triple<A,B,C>._1: A get() = this.first
val <A,B,C> Triple<A,B,C>._2: B get() = this.second
val <A,B,C> Triple<A,B,C>._3: C get() = this.third

val triple = Triple(1, "A", true)
println(triple._1)  // 1
println(triple._2)  // "A"
println(triple._3)  // true

And there you have it, simple!