본문 바로가기
코틀린/[Mapping] 매핑 작업

[Kotlin][Collection] getOrPut

by jinwo_o 2024. 9. 7.

값이 존재하고 null이 아닌 경우 지정된 키에 대한 값을 반환합니다. 그렇지 않으면 defaultValue 함수를 호출하고 해당 결과를 지정된 키 아래의 맵에 넣고 호출 결과를 반환합니다. 맵이 동시에 수정되는 경우 작업이 원자적으로 보장되지 않는다는 점에 유의하세요.

public inline fun <K, V> MutableMap<K, V>.getOrPut(key: K, defaultValue: () -> V): V {
    val value = get(key)
    return if (value == null) {
        val answer = defaultValue()
        put(key, answer)
        answer
    } else {
        value
    }
}


val map = mutableMapOf<String, Int?>()

println(map.getOrPut("x") { 2 }) // 2
// subsequent calls to getOrPut do not evaluate the default value
// since the first getOrPut has already stored value 2 in the map
println(map.getOrPut("x") { 3 }) // 2

// however null value mapped to a key is treated the same as the missing value
println(map.getOrPut("y") { null }) // null
// so in that case the default value is evaluated
println(map.getOrPut("y") { 42 }) // 42

 

getOrPut - Kotlin Programming Language

 

kotlinlang.org

'코틀린 > [Mapping] 매핑 작업' 카테고리의 다른 글

[Kotlin][Integer] toBinaryString  (0) 2024.09.07
[Kotlin][Map] getOrDefault  (0) 2024.09.07
[Kotlin][String] toBigDecimal  (0) 2024.09.04