본문 바로가기

IT/kotlin언어

[코틀린] let, with, run, also, apply 정리

안녕하세요 남갯입니다.



run과 let 등등 대충의 쓰임새만 알고 있고 따로 물어보면 사용처에 대한 정리가 되어 있지 않아 정리를 못했던거같은데


에서 다시 정리해서 포스팅해보려고 작성했습니다.






with <-> run


둘다 this

1. with는 입력하는 객체가 따로 필요없을때

2. run은 nullable일때


ex ) 


with(person){
this?.name
this?.age
}

person?.run{
this.name
this.age
}



let <-> run

 let은 it run은 this

다중문을 사용했을때 혹은 this가 모호할때

let을 사용 it말고 이름을 지정함으로써

let{ a1 ->
a1.let { a2->
//todo
}
}




also <-> let

also 객체 자체의 동일한 내용 이용하고 싶을때


"abc".let{
it
it.reversed()
}.let{
//여기서 반환된 let에 값은 cba
}

- let 

"abc".also{
it
it.reversed()
}.also{
//여기서 반환된 let에 값은 abc
// 기존의 'abc' 결과를 내린다.
}

also



apply

apply는 내부 프로퍼티나 동작을 세팅할때 사용 

Intent().apply {
action = intentAction
data = Uri.parse(intentData)
}







https://medium.com/@elye.project/mastering-kotlin-standard-functions-run-with-let-also-and-apply-9cd334b0ef84