본문 바로가기
💡 Kotlin

[kotlin] Pair

by 콩드로이드 2023. 1. 2.

Pair

 

두 변수를 하나로 묶어주는 클래스

(사용되는 경우가 많으므로 잘 알아두기)

data class Pair<out A, out B> : Serializable

 

 

 

Pair 클래스의 Properties

- first : Pair의 첫번째 값

- second : Pair의 두번째 값

 

 

 

Pair 생성하기

var (x,y) = Pair(3, 0.14)
var (x,y) = Pair<Int, Double>(3, 0.14)

자료형은 삭제해도 상관없다

 

 

 

Pair의 리스트화 toList()

var x = Pair<Int, Double>(3, 0.14).toList()

toList()를 통해 리스트화 가능 

 

 

 

두 값을 Pair화 시키려면 

val test : Pair<Int, Double> = 3 to 0.14

 

 

✔️ to 확장함수 사용

infix fun <A,B> A.to(that: B): Pair<A,B> = Pair(this, that)

﹒리시버타입에 제네릭이 적용되어서 모든 타입에 사용 가능 

 

to가 infix로 선언되어있기 때문에 연산자처럼 사용가능 

 

 

infix Notation(중위표기법)

  - 피연산자 연산자 피연산자 순서로 표현식을 구성하는 방식 

  - 함수를 연산자처럼 호출하는 방법 

'💡 Kotlin' 카테고리의 다른 글

[Kotlin] mutable Collection  (0) 2023.01.08
[Kotlin] Collection (List, Set, Map)  (0) 2023.01.03
[Kotlin] apply, let, with, also, run 비교 (Scope Function)  (0) 2022.07.14
[Kotlin] 배열  (0) 2022.07.02
[Kotlin/Android] Room 사용하기  (0) 2022.06.30