코딩하는 일용직 노동자

코틀린 ScopeFunction 종류와 역할 본문

안드로이드

코틀린 ScopeFunction 종류와 역할

bacass 2020. 5. 3. 17:30

let
객체의 null 체크에 주로 사용.

val userName: String? = ""
userName?.let {
    println("userName : $userName")
}


apply
객체의 생성과 동시에 값을 초기화 할때 주로 사용.

val textView = TextView(this).apply {
    text = "Hello World!!"
    setOnClickListener{}
}


run
이미 생성된 객체를 재접근해서 값을 셋팅할때 주로 사용.

textView.run {
    text = "안녕하세요"
    setOnClickListener{}
}


with
View 에 접근할때 주로 사용.

fun ViewHolder.onBindViewHolder() {
    with(binding){
        adapter = this@ItemAdapter
        data = item
    }
}



also 
apply 와 비슷하다. 
객체를 수정하거나 하지 않고, 디버깅을 위한 로깅을 하는등의 부가적인 일을 할때 사용.

val items = mutableListOf("사과", "바나나", "옥수수", "망고", "오렌지")
items.also {
    println("items: $it")
}.add("딸기")



apply, also 는 객체를 리턴한다.
let, run, with 는 람다 결과를 리턴한다.

'안드로이드' 카테고리의 다른 글

웹뷰 키보드 이슈 해결사례  (0) 2020.05.07
Android 10(Q) Scope Storage 에 관하여  (0) 2020.05.05
File Exploler 라이브러리  (0) 2020.05.03
Wifi ADB 디버깅 방법  (0) 2020.05.03
SSL 무시하기 처리.  (0) 2020.05.03