Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Conditional Control

Kotlin Conditional Control

Conditional control lets a program run different code for different situations.

Kotlin provides two conditional constructs, if and when; both are expressions, so their results can be assigned directly to variables.

This article covers the various forms of if, when branch conditions and exhaustiveness rules, and when guard conditions, which became stable in Kotlin 2.2.


if Expressions

The basic form of if is similar to Java's: the condition goes in parentheses, and the code in braces runs when the condition is true.

When a branch has only one statement, the braces can be omitted, but keeping them is recommended for readability.

Example

fun main

(

)

{

    val age

=

18

   

if

(

age

=

18

)

{

        println

(

"Adult"

)

   

}

   

// Braces can be omitted for a single statement

   

if

(

age

=

18

)

println

(

"Adult (braces omitted)"

)

   

// else runs when the condition is false

   

if

(

age

<

18

)

{

println

(

"Minor"

)

}

else

{

println

(

"Adult"

)

}

}


已成年

已成年(省略花括号)

成年

Kotlin's if is an expression rather than a statement, a difference that becomes clear in the next section.


if as an Expression Assigned to a Variable

Because if returns a value, you can assign its result directly to a variable, equivalent to the ternary operator in other languages.

When used as an expression, the else branch is required; otherwise the compiler cannot infer the variable's type.

Example

fun main

(

)

{

    val a

=

10

    val b

=

20

   

// Equivalent to Java's a > b ? a : b

    val max

=

if

(

a

b

)

a

else

b

    println

(

max

)

         

// 20

   

// The last line of a branch block is the return value

    val desc

=

if

(

a

b

)

{

        println

(

"a is greater"

)

       

"a"

   

}

else

{

        println

(

"b is greater"

)

       

"b"

   

}

    println

(

desc

)

       

// b

   

// Without else it can only be used as a statement, not assigned

   

// val bad = if (a > b) a // Compile error

}



20

b 更大

b

Note:Kotlin Has No Ternary Operator ? :; use an if expression instead. Written across multiple lines, it is actually clearer and easier to debug.


if-else if-else Chains

Multiple conditions can be chained with else if; the program checks them top to bottom and exits the chain as soon as one matches.

The following example converts a score into a grade.

Example

fun scoreToGrade

(

score

:

Int

)

:

String

{

   

return

if

(

score

=

90

)

{

       

"A"

   

}

else

if

(

score

=

80

)

{

       

"B"

   

}

else

if

(

score

=

60

)

{

       

"C"

   

}

else

{

       

"D"

   

}

}

fun main

(

)

{

    println

(

scoreToGrade

(

95

)

)

 

// A

    println

(

scoreToGrade

(

85

)

)

 

// B

    println

(

scoreToGrade

(

60

)

)

 

// C

    println

(

scoreToGrade

(

59

)

)

 

// D

}



A

B

C

D

The order of conditions matters: if score >= 60 comes first, every passing score will match it immediately and the later checks will never run.


Using Range Checks

Together with the in operator, ranges make conditions more intuitive and avoid a long chain of &&.

Since Kotlin 1.9 ..< has been stable; it represents a half-open range that excludes the right endpoint, equivalent to until.

Example

fun main

(

)

{

    val score

=

85

   

if

(

score in

90

..

100

)

{

        println

(

"Excellent"

)

   

}

else

if

(

score in

80

..

<

90

)

{

// ..< Excludes the right endpoint 90

        println

(

"Good"

)

   

}

else

if

(

score in

60

until

80

)

{

 

// until is equivalent to ..<

        println

(

"Pass"

)

   

}

else

{

        println

(

"Fail"

)

   

}

   

// !in means not within the range

    val c

=

'x'

   

if

(

c

!

in

'a'

..

'z'

)

{

        println

(

"Not a lowercase letter"

)

   

}

else

{

        println

(

"Is a lowercase letter"

)

   

}

}



良好

是小写字母

Range checks work for characters too; for example, checking whether a character falls within a certain letter range is much clearer than comparing code points one by one.


when Expressions

when replaces multiple else if clauses: it puts the subject in parentheses and each branch points to its result with an arrow.

when is also an expression, and the last line of a branch block is the return value, so it can be shortened with an expression-body function.

Example

fun describe

(

x

:

Any

)

:

String

=

when

(

x

)

{

   

1

->

"Number 1"

   

"Runoob"

->

"Runoob Tutorial"

    is

Long

->

"Long type"

   

!

is

String

->

"Not a string"

   

else

->

"other"

}

fun main

(

)

{

    println

(

describe

(

1

)

)

       

// Number 1

    println

(

describe

(

"Runoob"

)

)

// Runoob Tutorial

    println

(

describe

(

100L

)

)

   

// Long type

    println

(

describe

(

3.14

)

)

   

// Not a string

    println

(

describe

(

"hello"

)

)

 

// Other

}



数字 1

Runoob Tutorial

Long 类型

不是字符串

其他

Ways to Write Branch Conditions

when branch conditions are very flexible; the table below summarizes the common forms.

Syntax Example Description
Constant 1 -> ... Matches when equal to the subject
Multiple values with commas 1, 2, 3 -> ... Matches if any one value is equal
Within a range in 1..10 -> ... Matches when within the range
Outside a range !in 1..10 -> ... Matches when outside the range
Type checking is String -> ... Matches when of a certain type, with automatic smart casting
Type exclusion !is String -> ... Matches when not of a certain type
Any boolean expression n % 2 == 0 -> ... Matches when true in a subjectless when

Example

fun main

(

)

{

   

// Multiple values with commas: matches if any one is equal

    val day

=

6

    val type

=

when

(

day

)

{

       

1

,

2

,

3

,

4

,

5

->

"Weekday"

       

6

,

7

->

"Weekend"

       

else

->

"Invalid date"

   

}

    println

(

type

)

                     

// Weekend

   

// Range condition

    val score

=

85

    val grade

=

when

(

score

)

{

        in

90

..

100

->

"Excellent"

        in

80

..

<

90

->

"Good"

in

60

until

80

->

"Pass"

else

->

"Fail"

}

println

(

grade

)

// Good

   

// An is check enables smart casting, so members can be accessed directly inside the branch

    val value

:

Any

=

"www.runoob.com"

    val len

=

when

(

value

)

{

        is

String

->

value.

length

     

// Here value is already treated as a String

        is Int

->

value

       

else

->

0

   

}

    println

(

len

)

                     

// 14

}



周末

良好

14

Smart casting is an extra benefit of is branches: once the type has been checked, no manual cast is needed inside the branch.


Subjectless when

Without a subject, each branch condition is a boolean expression that matches as soon as it is true, equivalent to a chain of else if.

This form suits cases where the conditions share no common subject or where several different checks are needed.

Example

fun checkNumber

(

n

:

Int

)

:

String

=

when

{

    n

<

0

->

"Negative"

n

==

0

->

"Zero"

    n in

1

..

9

->

"Single digit"

   

else

->

"Multiple digits"

}

fun main

(

)

{

    println

(

checkNumber

(

3

)

)

   

// Negative

    println

(

checkNumber

(

0

)

)

   

// Zero

    println

(

checkNumber

(

7

)

)

   

// Single digit

    println

(

checkNumber

(

100

)

)

 

// Multiple digits

}



负数

零

个位数

多位数

A subjectless when used as an expression must have an else branch, because the compiler cannot tell whether the conditions cover every case.

Flowchart for choosing conditional branch syntax: when a conditional branch is needed, use if or if-else for a single boolean condition, when (x) { } for matching a value against multiple candidates, and when { } for multiple boolean conditions; both if and when are expressions that can be assigned directly, but when used as an expression must be exhaustive, and the else can be omitted when the subject is sealed, enum, or Boolean


Exhaustiveness of when

Exhaustiveness means whether all possible cases are covered, which depends on whether when is used in expression or statement position.

Used as an expression, when must produce a value and therefore must be exhaustive; used as a statement, ordinary types do not require exhaustiveness.

But for enum, sealed class, and Boolean subjects, Kotlin 1.6 issues a warning and Kotlin 1.7 reports an error, requiring exhaustiveness.

Subject Type As an Expression As a Statement
Ordinary types such as Int and String else is required May be non-exhaustive
enum Covering all enum values is enough; no else is needed Must be exhaustive (since Kotlin 1.7)
sealed class / sealed interface Covering all subtypes is enough Must be exhaustive (since Kotlin 1.7)
Boolean Covering both true and false is enough Must be exhaustive (since Kotlin 1.7)
Subjectless when else is required else is not required

Example

enum

class

Status

{

LOADING, SUCCESS, ERROR

}

// Enum subject: cover all enum values; no else is needed

fun message

(

status

:

Status

)

:

String

=

when

(

status

)

{

    Status.

LOADING

->

"Loading"

    Status.

SUCCESS

->

"Success"

    Status.

ERROR

->

"Failed"

}

// Boolean subject: cover both true and false; no else is needed

fun label

(

flag

:

Boolean

)

:

String

=

when

(

flag

)

{

   

true

->

"On"

   

false

->

"Off"

}

fun main

(

)

{

    println

(

message

(

Status.

SUCCESS

)

)

 

// Success

    println

(

label

(

true

)

)

             

// On

}



成功

开

Sealed classes are most commonly paired with when: the compiler can verify that all subtypes are covered, and adding a new subtype immediately reports a missing branch as an error.

Example

sealed

class

Result

data

class

Success

(

val data

:

String

)

:

Result

(

)

data

class

Failure

(

val reason

:

String

)

:

Result

(

)

fun render

(

result

:

Result

)

:

String

=

when

(

result

)

{

    is Success

->

"Success: ${result.data}"

    is Failure

->

"Failure: ${result.reason}"

}

fun main

(

)

{

    println

(

render

(

Success

(

"RUNOOB"

)

)

)

   

// Success: RUNOOB

    println

(

render

(

Failure

(

"Network timeout"

)

)

)

   

// Failure: Network timeout

}



成功:RUNOOB

失败:网络超时

Note:The else branch must come last. If any branch follows else, the compiler reports an error immediately.


when Guard Conditions

A guard condition lets you append a boolean check after a branch's main condition; the branch is entered only when both hold.

The syntax is to follow the main condition directly with if 表达式, with no arrow in between.

Guard conditions were implemented in Kotlin 2.0 and offered as a preview (KT-67787, requiring a command-line flag); they became stable in Kotlin 2.2 (KT-13626).

Example

sealed

interface

Response

data

class

Ok

(

val body

:

String

)

:

Response

data

class

Error

(

val reason

:

String

)

:

Response

fun handle

(

response

:

Response

)

:

String

=

when

(

response

)

{

   

// After the main condition holds, check the guard condition

    is Ok

if

response.

body

.

isNotEmpty

(

)

->

"Success: ${response.body}"

    is Ok

->

"Success but empty content"

    is

Error

if

response.

reason

.

isNotBlank

(

)

->

"Failure: ${response.reason}"

    is

Error

->

"Failure: reason unknown"

}

fun main

(

)

{

    println

(

handle

(

Ok

(

"RUNOOB"

)

)

)

   

// Success: RUNOOB

    println

(

handle

(

Ok

(

""

)

)

)

         

// Success but empty content

    println

(

handle

(

Error

(

"Timeout"

)

)

)

   

// Failure: Timeout

    println

(

handle

(

Error

(

"   "

)

)

)

   

// Failure: reason unknown

}



成功:RUNOOB

成功但内容为空

失败:超时

失败:原因未知

There are several restrictions on guard conditions worth noting.

First, guard conditions can only be used in a when with a subject; the subjectless form does not support them.

Second, multiple comma-separated conditions cannot be combined with a guard; for example, 0, 1 -> cannot be followed by if.

Third, when a branch needs multiple guards, combine them with && or || , and parentheses are recommended.

Example

sealed

interface

Animal

{

    data

class

Cat

(

val mouseHunter

:

Boolean

, val hungry

:

Boolean

)

:

Animal

    data

class

Dog

(

val breed

:

String

)

:

Animal

}

fun feed

(

animal

:

Animal

)

:

String

=

when

(

animal

)

{

    is Animal.

Dog

->

"Feed the dog"

   

// Combine multiple guard conditions with &&

    is Animal.

Cat

if

(

!

animal.

mouseHunter

&&

animal.

hungry

)

->

"Feed the cat"

    is Animal.

Cat

->

"Do not feed the cat"

}

fun main

(

)

{

    println

(

feed

(

Animal.

Dog

(

"Beagle"

)

)

)

                           

// Feed the dog

    println

(

feed

(

Animal.

Cat

(

mouseHunter

=

false

, hungry

=

true

)

)

)

 

// Feed the cat

    println

(

feed

(

Animal.

Cat

(

mouseHunter

=

true

, hungry

=

true

)

)

)

 

// Do not feed the cat

}



喂狗

喂猫

不喂猫

When the main condition holds but the guard does not, the program does not exit the when; it continues matching later branches.

For this reason,is Ok if ... is usually followed by an unguarded is Ok fallback, otherwise that type may have no branch to match.

Tip:Guard conditions also support else if syntax, for example else if animal.eatsPlants -> ..., which can handle multiple fallback branches. Guard conditions require a when with a subject; for a subjectless when, use && to merge the conditions into the branch instead.


Common questions

Here are the most common questions about conditional control.

When Is if's else Required?

else is required when if is used as an expression, that is, when its result is assigned to a variable or returned.

When if is used only as a statement and its return value is irrelevant, else can be omitted.

How to Choose Between when and if

When checking multiple values of the same subject, when is clearer than a long chain of else if.

When the conditions share no common subject, either an if-else chain or a subjectless when works; choose based on readability.

Why Does a when over an enum Compile Without else?

Because the compiler can verify that all enum values are covered, the when is already exhaustive.

If you later add a value to the enum and forget to add a branch, Kotlin 1.7 reports an error immediately; that is the value of exhaustiveness checking.

What Is the Difference Between a Guard Condition and an if Inside a Branch?

When a guard condition fails, matching continues with later branches.

Writing an if after entering a branch merely skips some code inside that branch and does not try other branches, so the two have completely different control flow.

Can when's else Be Placed in the Middle?

No, else must be the last branch.

If you truly need multiple fallback conditions, use a subjectless when with && and ||, or use the else if form inside a guard condition.