kotlin
  • Kotlin
  • Variable
  • Function
  • First Class Citizen
  • High Order Function
  • Pure Function
  • Call by Value, Call by Name
  • Null Safe
  • Generic
  • Expression
    • if - else
    • when
    • try - catch
    • while
    • for
  • Class
    • abstract
    • constructor
    • Data Class
    • Default Value
    • enum
    • inheritance
    • interface
    • open
    • property
    • sealed
  • Kotlin Standard
    • let
    • with
    • apply
    • run
    • also
    • takeIf
    • takeUnless
    • use
    • repeat
  • Collections
    • Mutable
    • Immutable
    • Collections
    • Aggregate operations
      • any
      • all
      • count
      • fold
      • foldRight
      • fold vs foldRight
      • forEach
      • forEachIndexed
      • max
      • maxBy
      • min
      • minBy
      • none
      • reduce
      • reduceRight
      • sum
      • sumBy
    • Filtering operations
      • drop
      • dropLast
      • dropWhile
      • dropLastWhile
      • filter
      • filterNot
      • slice
      • take
      • takeLast
      • takeWhile
    • Mapping operations
      • map
      • mapIndexed
      • flatMap
      • groupBy
    • Elements operations
      • contains
      • elementAt
      • elementAtOrElse
      • elementAtOrNull
      • first
      • firstOrNull
      • indexOf
      • indexOfFirst
      • indexOfLast
      • last
      • lastIndexOf
      • lastOrNull
      • single
      • singleOrNull
    • Generation operations
      • partition
      • plus
      • minus
      • zip
      • unzip
    • Ordering operations
      • reversed
      • sorted
      • sortedBy
      • sortedDescending
      • sortedByDescending
Powered by GitBook
On this page
  1. Kotlin Standard

apply

//T.() -> 마찬가지로 자기자신에 키워드 없이 그냥 접근가능
//Unit을 반환하는 함수를 받아서 apply는 자기자신을 반환한다
inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

val person = Person().apply {
    name = "ari"
    age = 24
}

println(person) //Person(name=ari, age=24)

AlertDialog.Builder(this).apply {
    setTitle(getString(R.string.title))
    setMessage(getString(R.string.message))
    setPositiveButton(getString(R.string.ok))
    { dlg, _ -> dlg.dissmis() })
    create()
    show()
}

  • type.apply { ... }

  • type T를 입력받아 { ... } 안을 수행하고 자기 자신을 반환한다

  • apply 는 생성과 동시에 어떤 추가적인 작업을 해줘야 할 때 유용하다

  • with는 이미 생성해 놓은 변수등을 가지고 연속적인 액션을 취해야 할 때 사용하면 유용하다

PreviouswithNextrun

Last updated 6 years ago