안드로이드

[코틀린] BackingField & Backing Properties

이손안나 2022. 10. 1. 22:11

💡 Property ?

- 코틀린에서 필드에 대한 기본 접근자 메소드를 자동으로 만들어주는데 때문에 필드 대신 프로퍼티라는 말을 사용.

 

Backing Field

  • 프로퍼티의 값을 저장하기 위한 필드 
  • 적어도 하나의 접근자가 기본으로 구현되는 접근자를 사용.
  • field 식별자를 이용하여 접근 가능.
var count = 0
    set(value) {
        if(value >= 0) field = value
    }

Backing Properties

  • 명시적으로 수행하려는 작업에서 사용.
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")
    }