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. Expression

if - else

  • Java 와 다르게 Kotlin 에서는 if, else 도 표현식이다. 따라서 if else 는 항상 반환값이 있다.

  • { } 블럭으로 있을 경우에는 마지막 줄의 값을 반환한다.

  • if, else 를 표현식으로 사용할 경우에는 if 가 있으면 항상 else 도 있어야 한다.

  • if, else를 표현식으로 사용할 수 있게 되므로서 java 의 삼항연산자를 대체할 수 있다. (코틀린에는 삼항연산자가 없다.)

//Java
//기존의 if else문의 사용방식.
int a = 5;
int b = 10;

int maxValue = a;

if (a > b) {
    maxValue = a;
} else {
    maxValue = b;
}
//Kotlin
val a = 5
val b = 10

var max: Int

if (a > b) {
    max = a
} else {
    max = b
}

//표현식으로서의 사용
val max = if (a > b) a else b

//각각 마지막줄의 a 와 b 를 반환한다.
val max = if (a > b) {
    print("Choose a")
    a
} else {
    print("Choose b")
    b
}
PreviousExpressionNextwhen

Last updated 6 years ago