-
[Kotlin] Scoping Functions apply vs. with, let, also, and runAndroid 2020. 11. 4. 15:06반응형
Here is the definition of all 5 functions:
inline fun <T, R> with(receiver: T, block: T.() -> R): R { return receiver.block() } inline fun <T> T.also(block: (T) -> Unit): T { block(this) return this } inline fun <T> T.apply(block: T.() -> Unit): T { block() return this } inline fun <T, R> T.let(block: (T) -> R): R { return block(this) } inline fun <T, R> T.run(block: T.() -> R): R { return block() }
using apply
val peter = Person().apply { // only access properties in apply block! name = "Peter" age = 18 }
The equivalent code without apply() would look like this:
val clark = Person() clark.name = "Clark" clark.age = 18
using also
class Book(author: Person) { val author = author.also { requireNotNull(it.age) print(it.name) } }
The equivalent code without also() would look like this:
class Book(val author: Person) { init { requireNotNull(author.age) print(author.name) } }
using let
getNullablePerson()?.let { // only executed when not-null promote(it) } val driversLicence: Licence? = getNullablePerson()?.let { // convert nullable person to nullable driversLicence licenceService.getDriversLicence(it) } val person: Person = getPerson() getPersonDao().let { dao -> // scope of dao variable is limited to this block dao.insert(person) }
The equivalent code without let() would look like this:
val person: Person? = getPromotablePerson() if (person != null) { promote(person) } val driver: Person? = getDriver() val driversLicence: Licence? = if (driver == null) null else licenceService.getDriversLicence(it) val person: Person = getPerson() val personDao: PersonDao = getPersonDao() personDao.insert(person)
using with
val person: Person = getPerson() with(person) { print(name) print(age) }
The equivalent code without with() looks like this:
val person: Person = getPerson() print(person.name) print(person.age)
using run
val inserted: Boolean = run { val person: Person = getPerson() val personDao: PersonDao = getPersonDao() personDao.insert(person) } fun printAge(person: Person) = person.run { print(age) }
The equivalent code without run() would look like:
val person: Person = getPerson() val personDao: PersonDao = getPersonDao() val inserted: Boolean = personDao.insert(person) fun printAge(person: Person) = { print(person.age) }
ref : medium.com/@fatihcoskun/kotlin-scoping-functions-apply-vs-with-let-also-run-816e4efb75f5
Kotlin Scoping Functions apply vs. with, let, also, and run
Functional-style programming is highly advocated and supported by Kotlin’s syntax as well as a range of functions in Kotlin’s standard…
medium.com
반응형'Android' 카테고리의 다른 글
[Android] 내부 테스트를 위한 내부 앱 공유 (0) 2020.11.13 [Kotlin] @JvmOverloads (0) 2020.11.06 [Kotlin] thread(스레드) (0) 2020.11.04 [Webview] All WebView methods must be called on the same thread (0) 2020.11.04 [Android] Html을 Textview에서 보여주기 in Kotlin (0) 2020.10.28