본문

171211(월) - Using scope functions

Using scope functions


apply

val foo = createBar().apply {
    property = value
    init()
}



also

receiver로 setting properties or function call 이외에 it을 사용하는경우 apply보다 prefer

class Baz {
    var currentBar: Bar?
    val observable: Observable

    val foo = createBar().also {
        currentBar = it
        observable.registerCallback(it)
    }
}

이미 multiple receivers in scope, you make calls on any outer receivers

class Foo {
    fun Bar.baz() {
        val stuff = callSomething().also {
            it.init()
            this@baz.registerCallback(it)
        }
    }
}



apply/with/run

- apply : 새로운 object를 선언함과 동시에 연속된 작업이 필요할 때 사용

- run : 이미 생성된 object에 연속된 작업이 필요할 때 사용

- with : run과 기능상 동일하지만 receiver로 전달할 object가 어디에 위치하는지만 다름 (ex: with(...) {...})


receiver가 nullable인경우 prefer apply / run over with

getNullable()?.run {
    init()
}

getNullable()?.apply {
    init()
}


returned value를 not used하면 run / with over apply

view.run {
    textView.text = "Hello World"
    progressBar.init()
}

with(view) {
    textView.text = "Hello World"
    progressBar.init()
}


✻ 위의 하나를 사용하되 consistently하게!



let

receiver를 trasform하는 method chain에서 let이 run보다 prefer한다. 

val baz: Baz = foo.let { createBar(it) }.convertBarToBaz()
// or with function references
val baz: Baz = foo.let(::createBar).convertBarToBaz()


공유

댓글