안드로이드 코틀린 : Pair, Triple, Data Class 여러 개의 반환 값을 가지는 메서드 또는 함수 만들기
Lucy Archive
Lucy 2023
2021. 4. 21. 06:08

Koltin : Pair, Triple, Data Class - Multi Return Function

이번 포스트는 코틀린 언어로

다수의 반환 값을 가지는 메서드 또는 함수를 만드는 방법을 만들기 위한 Pair, Triple, Data Class 활용법

에 대해 정리합니다.

 

Pair 와 Triple

일반적으로 함수(Function)은 1개의 결과값 또는 객체만 리턴합니다. 코틀린에서는 2개 또는 3개의 결과를 리턴할 수 있습니다. 이 때 사용되는 것이 Pair와 Triple 클래스 입니다. 

Pair와 Triple는 코틀린에서 쉽게 2개, 3개의 변수를 저장하기 위해 제공되는 일종의 데이터 클래스입니다. Pair와, Triple는 Tuples.kt에 아래와 같이 선언 되어 있습니다. 아래 코드에서 보는 것과 같이 Pair, Triple모두 data Class의 형태이고, toString() 메서드를 지원합니다. 공통적으로 toList() 함수를 사용해 Pair, Triple 객체를 배열로 변환이 가능합니다.

public data class Pair<out A, out B>(
    public val first: A,
    public val second: B
) : Serializable {

    /**
     * Returns string representation of the [Pair] including its [first] and [second] values.
     */
    public override fun toString(): String = "($first, $second)"
}

/**
 * Creates a tuple of type [Pair] from this and [that].
 *
 * This can be useful for creating [Map] literals with less noise, for example:
 * @sample samples.collections.Maps.Instantiation.mapFromPairs
 */
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

/**
 * Converts this pair into a list.
 * @sample samples.misc.Tuples.pairToList
 */
public fun <T> Pair<T, T>.toList(): List<T> = listOf(first, second)
public data class Triple<out A, out B, out C>(
    public val first: A,
    public val second: B,
    public val third: C
) : Serializable {

    /**
     * Returns string representation of the [Triple] including its [first], [second] and [third] values.
     */
    public override fun toString(): String = "($first, $second, $third)"
}

/**
 * Converts this triple into a list.
 * @sample samples.misc.Tuples.tripleToList
 */
public fun <T> Triple<T, T, T>.toList(): List<T> = listOf(first, second, third)

즉, 아래 코드와 같이 Pair 또는 Triple 클래스를 사용 할 수 있습니다. 아래 코드는 Pair에 저장되는 데이터를 String, Int 자료형 데이터를 사용했지만 클래스가 사용될 수도 있습니다. Pair 객체를 읽기 위해 first, second 또는 component1(), component2() 함수가 사용될 수 있습니다. 

fun main() {

    // Pair 객체 만들기
	val pair = Pair("Hello", 123)
    
    // Pair 객체 출력하기
    println("pair : $pair")
    println("pair.toString() : ${pair.toString()}")
    println("pair.first : ${pair.first}") // 첫 번째 값을 출력
    println("pair.component1() : ${pair.component1()}\n") // 첫 번째 값을 출력
    
    // 리스트로 변환
    val list = pair.toList()
    println("list : $list\n")
        
    // 개별 변수에 저장
    var (string, number) = Pair("Hello", 123)
    println("string : $string")
    println("number : $number")
}

위 코드의 결과 값은 아래와 같습니다. 

pair : (Hello, 123)
pair.toString() : (Hello, 123)
pair.first : Hello
pair.component1() : Hello

list : [Hello, 123]

string : Hello
number : 123

Pair를 사용한 반환값 2개 함수 만들기

2개의 값을 반환하는 함수, 메서드를 만드는 경우 Return되는 타입만 명시적으로 정의하면 됩니다.

fun main() {
    
    var (first, second) = pairSquare(10,100)
    
    println("first : $first")
    println("second : $second")
    
}

fun pairSquare(first: Int, second: Int): Pair<Int, Int>{
    return Pair(first*first, second*second)
}

Triple를 사용한 반환값 3개 함수 만들기

Triple은 Pair와 사용법이 동일합니다.

fun main() {

    var (first, second, third) = tripleSquare(1,2,3)
    
    println("first : $first")
    println("second : $second")
    println("third : $third")
    
}

fun tripleSquare(first : Int, second : Int, third : Int) : Triple<Int, Int, Int>{
    return Triple(first*first, second*second, third*third)
}

4개 이상의 반환 값 : DataClass 활용

4개 이상의 반환 값을 가지는 함수를 만들기 위해 Data Class를 사용 할 수 있습니다. 위에서 설명한 Pair 와 Triple도 Data Class 이기 떄문에 사용법은 동일합니다. 17번 라인의 ... 부분에 원하는 데이터를 불러오거나 가공하는 코드를 넣으면 됩니다. 

data class Person(val name : String, val gender : String, var old : Int, var grade : Int)

fun main() {
    
    var person = getStudentInfo()
    println(person)
    
}

fun getStudentInfo(): Person{
   
    var name : String 
    var gender : String
    var old : Int
    var grade : Int
    
    ........
    
    return Person(name, gender, old, grade)
}

※ 4개 이상의 반환 값을 가지는 함수를 만들기 위해 꼭 Data Class를 사용하지 않고, 배열로 반환하는 등의 방법을 사용할 수 도 있습니다. 

끝까지 읽어 주셔서 감사합니다.^^

관련포스트

🤞 안드로이드(코틀린) 앱 제작하기 관련글 목록 보기

🤞 안드로이드(코틀린) 팁 관련글 목록 보기

🤞 안드로이드 문법 관련글 목록 보기