Backing Field와 Backing Properties

2019. 2. 12. 09:00Programming/Kotlin

반응형

필사를 하던 중에 잘 이해가 가지 않는 개념이 있어서 내용을 정리한다.

구글링을 해봤지만 잘 번역된 검색을 발견하지 못해서, 어설프나마 검색을 통해 이해한 내용을 취합하여 정리한 내용이다.

Backing Field

Kotlin의 Bakcing Field는 getter/setter에 기본적으로 생성되는 속성(property)이다. Kotlin에서는 Class내의 property에 값을 할당할때는 내부적으로 setter가, 값을 불러올때는 getter가 호출된다. 다음의 코드를 참조하도록 하자.

class User{
  var name: String
    get() = name
    set(value) {name = value}
}

위의 코드에서 User.name에 “BlackBear”라는 값을 할당하게되면, User.name.set(“BlackBear”)를 호출한 것과 같다. 이렇게 되면 name의 setter에서 name에 “BlackBear”라는 값을 할당하면서 다시 setter를 호출하게되고, 결과적으로 setter가 재귀적으로 호출된다. 결국 이는 StackOverflowException을 발생시킨다. (현재 Kotlin버전에서는 수정됐다는 이야기가 있다. 이 내용은 테스트 후 추가하도록 하겠다.)

이를 위해서 Kotlin에서는 Backing Field를 제공한다. Backing Field는 accessor(getter/setter)안에서 field 키워드를 사용하여 접근할 수 있다. 위의 예시를 field를 사용하면 다음과 같다.

class User{
  var name: String
    get() = field
    set(value) {field = value}
}

Backing Properties

If you want to do something that does not fit into this “implicit backing field” scheme, you can always fall back to having a backing property:

private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
    get() {
        if (_table == null) {
            _table = HashMap() // Type parameters are inferred
        }
        return _table ?: throw AssertionError("Set to null by another thread")
    }

In all respects, this is just the same as in Java since access to private properties with default getters and setters is optimized so that no function call overhead is introduced.

Backing Field in Kotlin - Explain, Noman Rafique
Backing Field, Kotlinlang.org
Backing Properties in Kotlin, Ihor Kucherenko
Backing Properties, Kotlinlang.org

반응형