Server

Kotlin의 Pair와 Triple

니용 2020. 7. 2. 16:30
반응형

Author: 니용

 


 

Kotlin에서 제공하는 객체 타입 중 연관 타입끼리 관계가 없어도 2개 혹은 3개를 쌍으로 가지고 있는 객체가 있습니다. 

2개인 경우 Pair라고 하고, 3개인 경우는 Triple이라고 합니다.

 

Pair

val pair1 = Pair("Same", "Type")
val pair2 = Pair("Another Type", 8080)

// 명시적 타입 선언
val pair3 = Pair<String, String>("Same", "Type")
val pair4 = Pair<String, Int>("Another Type", 8080)

getter .first / .second 또는 .component1() / .component2()로 접근 가능합니다.

val pair = Pair("String Val", 838);
pair.first // "String Val"
pair.second // 838

pair.first == pair.component1() // true
pair.second == pair.component2() // true

Pair를 이렇게 만들 수도 있습니다.

val pair : Pair<String, String> = "Start" to "End"
val (start, end) = "Start" to "End"

 

Triple

Pair와 크게 다르지 않습니다. 하나가 더 붙은 꼴입니다.

val triple = Triple("String Val", 838, true);
triple.first // "String Val"
triple.second // 838
triple.third // true

triple.first == triple.component1() // true
triple.second == triple.component2() // true
triple.third == triple.component3() // true

 

반응형