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

takeIf

// (T) -> it으로 접근가능
inline fun <T> T.takeIf(predicate: (T) -> Boolean)
: T? = if (predicate(this)) this else null

// T로 부터 takeIf 를 사용가능 반환값 T는 Nullable
// Boolean 을 반환하는 predicate 함수를 하나 받아서 그 함수의 반환값이 true 면 자기 자신을 반환하고
// false 면 null을 반환한다.
// 보통 체크하는것을 predicate 라는 이름으로 많이 사용한다. 

// false 인 경우
val ari = person.takeIf { it.name == "ari" }
println(ari) // null

// true 인 경
val gold = person.takeIf { it.name == "gold" }
println(gold) // Person(name=gold, age=18)

val default = person.takeIf { it.name == "ari" } ?: Person("ari", 24)
println(default) //Person(name=ari, age=24)
PreviousalsoNexttakeUnless

Last updated 6 years ago