[android : kotlin] 코틀린 apply 사용방법 및 총정리 : 스코프 함수(Scope Functions)
코틀린 apply 사용방법
apply와 같은 스코프함수는 람다식을 사용합니다. 중괄호{}로 묶어서 사용하게 됩니다. 중괄호 안에서 임시 범위가 형성됩니다. 이 범위에서는 이름없이 객체에 접근 할 수 있습니다. 그럼 왜 쓸까요? 특정 객체를 생성과 동시에 초기화를 할때 사용합니다.
다음 예제 코드들의 실행결과름 참고하세요.
class Person {
constructor( name: String, age: Int, city: String){
this.name = name
this.age = age
this.city = city
}
constructor( name: String) {
this.name = name
}
var name: String? = null
var age = 0
var city: String? = null
}
fun main() {
val tePerson = Person("IU").apply {
age = 27
city = "Seoul"
}
println("${tePerson.name}")
}
[실행결과]
IU
apply를 사용하면 선언한 객체이름을 생략하고 접근이 가능합니다.
//일반적인 사용방법
val layoutParam = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT
, LinearLayout.LayoutParams.WRAP_CONTENT)
layoutParam.gravity = Gravity.CENTER_HORIZONTAL
layoutParam.topMargin = 100
layoutParam.bottomMargin = 200
//apply를 사용하면 layoutParam를 생략하고 객체 내부 속성에 접근이 가능합니다.
val param = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT
, LinearLayout.LayoutParams.WRAP_CONTENT).apply{
gravity = Gravity.CENTER_HORIZONTAL
topMargin = 100
bottomMargain = 200
}
exoPlayer = SimpleExoPlayer.Builder(this).build().apply {
setAudioAttributes(uAmpAudioAttributes, true)
setHandleAudioBecomingNoisy(true)
addListener(ExoPlayerListener())
}
val loginParams = Bundle().apply {
putString(LOGIN_EMAIL, email)
putString(LOGIN_PASSWORD, password)
}
fun dbInsert(user: UserInfo) = SqlBuilder().apply {
append("INSERT INTO TB_USER (name, email, age) VALUES ")
append("(?", user.name)
append(",?", user.email)
append(",?)", user.age)
}.also {
print("실행결과: $it")
}
코틀린 스코프함수 정리
| 스코프 함수 | 블록내 argument ( 중괄호 안{} ) | 리턴 값 |
| T.let() | it | R (블록 안의 실행 결과를 리턴) |
| T.also() | it | T (블록 안의 실행결과와 상관없이 T를 피턴) |
| T.run() | this | R |
| run() | this | R |
| with(T) | this | Unit |
| T.apply() | this | R |
[REFERENCE]
kotlinlang.org/docs/reference/scope-functions.html#scope-functions
[코틀린 더 알아보기]
[android : kotlin] 코틀린 .let 사용법 예제 및 총정리 : 스코프 함수(Scope Functions)

