Kotlin Ternary Operator

Learn via video courses
Topics Covered

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Overview

Making decisions and selecting between multiple options is a fundamental task in computer programming. The ternary operator provides a concise way to express conditional statements in various programming languages. It allows developers to evaluate a condition and return one of two values based on whether the condition is true or false. A ternary operator is particularly useful for simplifying code and enhancing readability by converting it into a more compact form.

To know how we implement a ternary operator in Kotlin, let's dive in.

Ternary operator in Kotlin

When it comes to expressing conditional logic in programming, many languages offer a succinct and elegant solution known as the ternary operator. However, Kotlin takes a slightly different approach. Unlike some other languages, ternary operator in Kotlin is not provided as a built-in feature. However, Kotlin offers graceful substitutes that deliver comparable functionality.

However, this apparent omission of the ternary operator in Kotlin doesn't hinder its capability to elegantly handle conditional expressions. Instead of relying on a standalone ternary operator, Kotlin offers a variety of constructs that together accomplish the same tasks.

Free Courses by top Scaler instructors
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course

if and when Expressions

Unlike other programming languages, both if and when are expressions in Kotlin. What this means is that the outcome of these expressions can be assigned to a variable.

Leveraging this characteristic, both if and when can serve as alternatives to the ternary operator in Kotlin, each in its unique manner.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

Using if-else

Let us explore utilizing the if expression as a substitute for the ternary operator in Kotlin.

Consider the following code snippet.

Code:

In this example, if the value of a is true, the result variable is assigned the boolean value true. Otherwise, it receives the boolean value false.

It is important to recognize that the resultant data type depends on the expression found on the right side. Generally, the type defaults to Any. For instance, if the right-side expression holds a String type, the outcome will also be of String type. Consider the following code snippet.

Code:

Using when

Utilizing the when expression, we can construct a pseudo-ternary operator in Kotlin as well. Here is how we go about doing it.

Code:

This code snippet above is simple, readable and direct. When the condition (num%2 == 0) evaluates to true, the result is set to "Even". Conversely, when the condition is false, the result becomes "Odd". The behaviour is similar to what the ternary operator offers in other programming languages.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Elvis Operator

We often use if expressions to retrieve a non-null value or provide a default one in case of null. Consider the following example.

Code:

This behavior can also be achieved using when expressions. Consider the following code snippet.

Code:

Given the frequency of its usage, Kotlin offers a dedicated operator for this scenario.

Code:

This operator, known as the Elvis operator (?:), exhibits a simple yet powerful functionality. It returns the operand if it's non-null; otherwise, it returns the default value present on the right side of the operator.

DSL

Certainly, there's a strong urge to build something similar to a ternary operator using Kotlin's DSL (Domain-Specific Language). But due to Kotlin's strict rules, it's not possible to perfectly recreate the exact way traditional ternary operators work.

Conclusion

Here are the key takeaways from this article:

  1. There's no built-in support for a ternary operator in Kotlin. Other languages have this functionality for concise conditional expressions.
  2. In Kotlin, both if and when serve as expressions, allowing you to assign their results to variables. This characteristic enables you to achieve a behaviour like ternary operator in Kotlin without a dedicated operator.
  3. Kotlin introduces the Elvis operator (?:), which serves as a succinct means to handle nullability and provide default values. It's a powerful tool for achieving ternary-like functionality when dealing with null values.
  4. Replicating the traditional ternary operator in Kotlin by creating DSL is challenging due to Kotlin's stringent language rules.