Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

Dev.

Kotlin - 늦은 초기화 (1) lateinit 본문

Kotlin

Kotlin - 늦은 초기화 (1) lateinit

Pppdw 2019. 11. 12. 10:10
//1. 클래스 생성과 동시의 변수 초기화
val index = 1

//2. lateinit property 사용의 예
lateinit var model: QuizDetailViewModel

//3. lazy property 사용의 예
val answer: MutableLiveData<String> by lazy {
    MutableLiveData<String>()
}

 

위 코드의 1번 상황은 재 접근 및 재 사용 시 빠르게 접근하여 메모리,성능적 이점을 확보할 수 있다.

하지만 1회성 변수, 다시 사용하지 않을 변수 등 의 상황에서 생성과 동시의 초기화를 하면 메모리,성능적 손해를 볼 수 있다.

 

아래는 위 의 상황이 아닌 늦은 초기화를 지원해주는 property 에 대한 설명이다.

 

1. lateinit property

정리하자면 Non-null property 의 지원으로 null 로 선언된 필드값(값이 지정되지 않은) 을 컴파일 단계에서 인정되도록 한다.

 

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

<출처 -> https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties>

 

class QuizDetailActivity : AppCompatActivity(){

    lateinit var model: QuizDetailViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_quiz_detail)

        model = ViewModelProviders.of(this).get(QuizDetailViewModel::class.java)

    }
}

 

2. lateinit 을 사용하기 위한 조건

- var 타입의 변수에 사용할 수 있지만,

- primitive type 이 아니어야 하고, 

- getter/setter 선언이 불가하고,

- null 초기화가 불가하며,

- 초기화 전 시점에서 변수에 대한 접근 시 Exception 이 발생된다. ( lateinit property subject has not been initialized )

 

The modifier can be used on var properties declared inside the body of a class (not in the primary constructor, and only when the property does not have a custom getter or setter) and, since Kotlin 1.2, for top-level properties and local variables. The type of the property or variable must be non-null, and it must not be a primitive type.

Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn't been initialized.

<출처 -> https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties>

 

 

3. lateinit var 의 initialized 확인 (Kotlin 1.2 이상)

.isInitialized 의 활용 (prefix 로 :: 키워드를 붙여줘야 접근 가능하다.)

 

model = ViewModelProviders.of(this).get(QuizDetailViewModel::class.java)
if(::model.isInitialized){
    model.quiz.observe(this, observeListener)
}

 

 

'Kotlin' 카테고리의 다른 글

Kotlin - 'when expression', 코틀린의 switch-case  (0) 2019.11.19
Comments