Skip to content

Instantly share code, notes, and snippets.

@eyedroot
Created August 13, 2019 06:35
Show Gist options
  • Save eyedroot/16a66c1ddb19f9890f4c393ecd356699 to your computer and use it in GitHub Desktop.
Save eyedroot/16a66c1ddb19f9890f4c393ecd356699 to your computer and use it in GitHub Desktop.
/**
* 위임 프로퍼티가 유용하게 사용되는 몇 가지 기능
*
* by Lazy()
*
* '지연 초기화(Lazy Initialization)'는 프로퍼티의 초기화를 객체를 생성할 때 하지 않고
* 필요할 때 초기화하는 패턴이다.
*
* 예를 들어 객체 생성시 서버에 연결하고, 연결이 완료되면 데이터를 수신해서
* 프로퍼티에 값을 넣는 경우
*
*/
data class Address(val name: String, var phone: String, var addr: String = "")
fun loadAddrBook(p: Person): List<Address> {
return listOf()
}
open class Person(open val name: String) {
private var _addrBook: List<Address>? = null
open val addrBook: List<Address>
get() {
if (_addrBook == null) _addrBook = loadAddrBook(this)
return _addrBook!! // absolutely, I'm not null
}
}
/**
* 위에 소스코드는 일반적인 Lazy코드의 작성법이다. 근데 또 너무 길어서 코틀린에서는
* 간단한 방법을 제공해줌
*/
class Person2(override val name: String) : Person(name) {
override val addrBook by lazy({ loadAddrBook(this) })
/**
* lazy() 메서드에는 몇 가지 제약사항이 있는데
* var 타입의 프로퍼티에는 사용할 수 없다는 것
* (최초에 한 번만 초기화되므로 변경 될 수 없다)
*/
}
fun main(args: Array<String>?) {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment