Question

Kotlin Ternary Conditional Operator Equivalent Explained

kotlinconditional-operator

Question

What is the Kotlin equivalent of the following conditional expression?

a ? b : c

This syntax is not valid in Kotlin, so how should the same logic be written correctly?

Short Answer

By the end of this page, you will understand why Kotlin does not have a traditional ternary operator, how if works as an expression instead, and how to write concise conditional logic in idiomatic Kotlin.

Concept

In many languages such as Java, JavaScript, and C, the ternary conditional operator is written like this:

condition ? valueIfTrue : valueIfFalse

Kotlin does not include a separate ternary operator. Instead, Kotlin uses if as an expression.

That means if does not just control program flow; it can also produce a value.

The Kotlin equivalent of:

a ? b : c

is:

if (a) b else c

This works because in Kotlin, if can return one value when the condition is true and another value when the condition is false.

Example:

val result = if (score >= 50) "Pass" else "Fail"

Here, the if expression returns either "Pass" or "Fail", and that returned value is assigned to result.

Why Kotlin does this

Kotlin was designed to reduce unnecessary language features when an existing feature can already do the job clearly. Since if can already return a value, a separate ternary operator is not needed.

This matters in real programming because conditional value selection is extremely common:

  • choosing display text
  • selecting a default value
  • deciding status labels
  • returning one of two results
  • assigning values based on validation

Kotlin keeps this simple by making if powerful enough to cover both statement-style and expression-style usage.

Mental Model

Think of if in Kotlin as a fork in the road that hands you a result.

  • If the condition is true, you take the left road and get one value.
  • If the condition is false, you take the right road and get a different value.

In some languages, the ternary operator is a compact shortcut for this decision. In Kotlin, the regular if already does that job.

So instead of thinking:

condition ? this : that

think:

if (condition) this else that

It is the same decision, just written in Kotlin's style.

Take Quiz

Syntax and Examples

The core Kotlin syntax is:

if (condition) valueIfTrue else valueIfFalse

Basic example

val max = if (a > b) a else b

This assigns:

  • a if a > b is true
  • otherwise b

With strings

val message = if (isLoggedIn) "Welcome back" else "Please sign in"

With blocks

If the logic is larger, you can use blocks:

val result = if (temperature > 30) {
    "Hot"
} else {
    "Cool"
}

The last expression in each block becomes the returned value.

Equivalent of ternary logic

val value = if (a) b else c

This is the direct Kotlin replacement for:

// Java-style idea, not valid Kotlin
// a ? b : c

Important rule

When using if as an expression, you usually need both branches:

val label = if (count > 0) "Items available" else "Out of stock"

Without else, Kotlin cannot always determine what value should be produced.

Step by Step Execution

Consider this example:

val age = 16
val status = if (age >= 18) "Adult" else "Minor"
println(status)

Step by step

  1. age is assigned the value 16.
  2. Kotlin evaluates the condition age >= 18.
  3. 16 >= 18 is false.
  4. Because the condition is false, Kotlin chooses the else branch.
  5. The if expression returns "Minor".
  6. That value is assigned to status.
  7. println(status) prints:
Minor

Another trace

val x = 10
val y = 7
val bigger = if (x > y) x else y
println(bigger)

Execution:

  1. x is 10
  2. y is 7
  3. Check x > y
  4. 10 > 7 is true
  5. Kotlin returns x
  6. bigger becomes 10
  7. Output is:
10

Real World Use Cases

Conditional expressions appear everywhere in Kotlin applications.

UI text selection

val buttonText = if (isSaving) "Saving..." else "Save"

Useful in Android or desktop apps when labels depend on state.

Validation results

val status = if (email.isBlank()) "Email required" else "Valid"

Common in forms and input checking.

API response mapping

val message = if (response.isSuccessful) "Request succeeded" else "Request failed"

Used when converting backend results into readable app messages.

Data formatting

val displayName = if (name.isNotBlank()) name else "Anonymous"

Helpful when choosing fallback values.

Business rules

val shippingCost = if (total >= 50) 0 else 5

Common in pricing, discounts, and order logic.

Take Quiz

Real Codebase Usage

In real Kotlin codebases, developers often use if expressions for short, readable decisions.

Assigning computed values

val baseUrl = if (isProduction) PROD_URL else DEV_URL

This is common in configuration code.

Guard-style decisions

fun getDisplayName(name: String?): String {
    return if (name.isNullOrBlank()) "Guest" else name
}

This pattern is frequently used for fallback values.

Returning values directly

fun parity(n: Int): String {
    return if (n % 2 == 0) "Even" else "Odd"
}

Instead of creating a temporary variable, developers often return the if expression directly.

Using blocks for more complex branches

val result = if (user != null) {
    user.name.uppercase()
} else {
    "UNKNOWN"
}

Combining with null checks

val title = if (input == null) "No title" else input

This appears often alongside Kotlin's null-safety features.

When developers avoid it

If the condition becomes too complex or deeply nested, developers usually switch to:

  • a normal multi-line if/else
  • when
  • a helper function

The goal is readability, not just short code.

Common Mistakes

1. Trying to use the Java-style ternary operator

Broken code:

val result = a ? b : c

Why it fails:

  • Kotlin does not support ? : as a ternary operator.

Correct Kotlin:

val result = if (a) b else c

2. Forgetting parentheses around the condition

Broken code:

val result = if a b else c

Correct:

val result = if (a) b else c

3. Omitting else when a value is needed

Broken code:

val message = if (isReady) "Ready"

Why it fails:

  • Kotlin expects a value for both outcomes when if is used as an expression.

Correct:

val message = if (isReady) "Ready" else "Not ready"

4. Returning different types by accident

Problematic code:

val result = if (flag) 1 else "one"

Why this is a problem:

  • Kotlin will infer a very broad type such as Any, which is often not what you want.

Better:

val result = if (flag) "1" else "one"

5. Making expressions too complex

Hard-to-read code:

val label = if (user != null && user.isActive && user.age > 18) "Allowed" else "Blocked"

This is valid, but long conditions can be harder to maintain.

Better:

val isAllowed = user != null && user.isActive && user.age > 18
val label = if (isAllowed) "Allowed" else "Blocked"

Comparisons

ConceptSyntaxReturns a value?Kotlin supportBest use
Kotlin if expressionif (cond) a else bYesYesChoose between two values
Java-style ternarycond ? a : bYesNoNot available in Kotlin
Kotlin if statementif (cond) { ... } else { ... }Can be used as bothYesControl flow or value selection
Kotlin when expressionwhen (x) { ... }YesYesMultiple branches

if vs when

  • Use if for simple true/false decisions.
  • Use when when there are many possible branches.

Example:

val grade = when (score) {
    in 90..100 -> "A"
    in 80..89 -> "B"
    else -> "C"
}

Kotlin vs Java style

Java:

String result = isMember ? "Yes" : "No";

Kotlin:

val result = if (isMember) "Yes" else "No"

Same idea, different syntax.

Take Quiz

Cheat Sheet

// Java-style ternary does NOT exist in Kotlin
// condition ? a : b

// Kotlin equivalent
if (condition) a else b

Quick rules

  • Kotlin has no ternary operator.
  • Use if as an expression instead.
  • if can return a value.
  • When assigning the result, usually include both if and else.
  • The last expression in each block is the returned value.

Common patterns

val max = if (a > b) a else b
val text = if (name.isBlank()) "Unknown" else name
val fee = if (total >= 50) 0 else 5

Multi-line form

val result = if (condition) {
    doSomething()
    "Yes"
} else {
    doSomethingElse()
    "No"
}

Prefer when for many branches

val type = when (code) {
    1 -> "Admin"
    2 -> "User"
    else -> "Guest"
}

FAQ

Does Kotlin have a ternary operator?

No. Kotlin does not have a separate ?: ternary conditional operator like Java or JavaScript.

What should I use instead of a ? b : c in Kotlin?

Use:

if (a) b else c

Why did Kotlin remove the ternary operator?

Because Kotlin's if already works as an expression and can return a value, so a separate ternary operator is unnecessary.

Is if in Kotlin an expression or a statement?

It can be both. It can control flow like a statement and also return a value like an expression.

Do I always need else in Kotlin if expressions?

If you want if to produce a value, yes, you usually need else.

Can I use blocks inside a Kotlin if expression?

Yes. The last expression inside each block becomes the returned value.

When should I use when instead of if?

Use when when you have more than two branches or many possible conditions.

Take Quiz

Mini Project

Description

Build a small Kotlin program that decides what label to show for a user's age. This project demonstrates how to replace ternary-style thinking with Kotlin's if expression in a practical way.

Goal

Create a program that assigns and prints user status labels using Kotlin if expressions.

Requirements

  1. Create an age variable.
  2. Use an if expression to assign either "Adult" or "Minor".
  3. Print the result.
  4. Add a second example that assigns a pass/fail message from a score.
Take Quiz

Keep learning

Related questions

View more