ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Kotlin] Pair or Map
    Kotlin 2021. 1. 24. 19:03

    Kotlin의 Map과 Pair에 대하여 알아보자. 

     

    Map

    - 코틀린의 Map은 key와 value로 구성되어있는 dictionary 형태라고 생각하면 된다. 

    - key는 유니크한 값이며, 유니크한 key는 다른 key와 동일한 value를 가질 수 있으며,
      정의된 key를 통해 삽입 삭제 또한 가능하다. 

    - 코틀린의 Map은 Collection 인터페이스를 상속하고 있지 않지만, 코틀린의 collection type으로 Map은 지정되어있다. 

    kotlin collection

    Map 생성 

    val maps = mapOf(1 to "one",2 to "two",3 to "three")
    

     

     Map을 생성하기 위한 mapOf은 stlib에서 아래와 같이 나와있다. 

    /**
     * Returns a new read-only map with the specified contents, given as a list of pairs
     * where the first value is the key and the second is the value.
     *
     * If multiple pairs have the same key, the resulting map will contain the value from the last of those pairs.
     *
     * Entries of the map are iterated in the order they were specified.
     *
     * The returned map is serializable (JVM).
     *
     * @sample samples.collections.Maps.Instantiation.mapFromPairs
     */
    public fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> =
        if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap()

     


    Pair

    - map과 동일하게 pair 또한 한 쌍으로 이루어져 있다. 다른 점은 pair의 first second 모두 value를 뜻하는 것이다. 

    - Pair은 코틀린의 표준 라이브러리 클래스로 두 원소로 이루어진 순서쌍을 표현한다. 

    data class Pair<out A, out B> : Serializable
    Parameters
    A - type of the first value.
    B - type of the second value.

     

    Pair 생성

    val mPair : Pair<Int,String> = Pair(1,"one")
    val (number,name) = 1 to "one"  //Destructuring Declarations

     

    pair을 만들때 보통 to라는 inifx 함수를 이용하여 생성한다. 

    /**
     * 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) fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

    infix 함수란 2개의 변수 가운데 오는 함수를 말하는데, 
    여기서의 to 를 보면 제네릭으로 인자를 받고 이루어져 있고 Pair 인스턴스를 반환한다. 


    Destructuring Declarations ?

    - 객체를 여러 변수로 분해하는 것이다. 

    - 한 번에 여러 변수를 만들 수 있고 새로운 2가지 변수를 독립적으로 사용할 수 있음을 나타낸다. 

    - pair의 first , pair의 second로 접근하는 것보다 가독성 있지 않을까 생각한다. 

     


    Ref

    Kotlibn Collection 

     

    Collections Overview - Kotlin Programming Language

     

    kotlinlang.org

    Kotlin Pair

     

    Pair - Kotlin Programming Language

     

    kotlinlang.org

    Kotlin Destructuring Declarations

     

    Destructuring Declarations - Kotlin Programming Language

     

    kotlinlang.org

     

    LIST

    'Kotlin' 카테고리의 다른 글

    [Kotlin] vararg (Variable number of arguments) 가변인자  (0) 2021.05.09
    [Kotlin] none,any,all,contains  (0) 2021.03.30
    [Kotlin] Data Class  (0) 2020.04.28
    [Kotlin]FoldRight && Fold  (0) 2019.12.27
    [Kotlin] Reference and Reflection  (0) 2019.10.22

    댓글

Designed by Tistory.