Kotlin 속성 위임: var < proverty-name>: < property-type> by < delegate-class>()
kotlin에는 var 속성에 자동으로 getter와 setter 함수가 생성됩니다.
val의 경우에는 getter만 생성됩니다.
아래와 같이 by를 사용하여 위임할경우 getter와 setter의 책임을 다른 클래스에 넘길 수 있습니다.(대리자 클래스)
private val viewModel: GameViewModel by viewModels()
private var viewModel: GameViewModel()
UI에 표시되어야 하는 내용은 ViewModel로 옮긴다
private var로 설정하여 외부에서 접근을 막는다.
class GameViewModel : ViewModel() {
private var score = 0
private var currentWordCount = 0
private var currentScrambledWord = "test"
...
}
//ex1
// Declare private mutable variable that can only be modified
// within the class it is declared.
private var _count = 0
// Declare another public immutable field and override its getter method.
// Return the private property's value in the getter method.
// When count is accessed, the get() function is called and
// the value of _count is returned.
val count: Int
get() = _count
//ex2
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")
}
viewModel의 수명주기는 Activity와 Fragment의 범위가 유지되는 동안 유지됩니다.
