Blog Infos
Author
Published
Topics
, , , ,
Published

Finally Ternary Operator in kotlin 2.0

In Kotlin, the Elvis operator (?:) combined with smart casts can indeed be used to create a construct similar to the ternary operator in Java (condition ? trueExpression : falseExpression). While Kotlin doesn’t have a built-in ternary operator, the Elvis operator and smart casts provide a concise and expressive way to achieve the same functionality.

Java Ternary Operator

In Java, the ternary operator looks like this:

String result = (condition) ? "True value" : "False value";
Kotlin Equivalent Using Elvis Operator and Smart Casts

In Kotlin, you can achieve similar behavior with the Elvis operator and smart casts. Here’s how you can do it:

Example

Let’s consider a function that checks if a given object is a string and returns its length, or returns -1 if it’s not a string.

fun getStringLength(obj: Any?): Int {
    return (obj as? String)?.length ?: -1
}
Explanation
  1. Safe Cast (as?):
  • obj as? String attempts to cast obj to a String. If the cast is not possible, it returns null instead of throwing a ClassCastException.

2. Smart Cast with Elvis Operator (?:):

  • (obj as? String)?.length safely calls the length property if obj is successfully cast to a String. If obj is not a String, the expression evaluates to null.
  • The Elvis operator ?: then provides a fallback value -1 if the left-hand side expression is null.
Combining with a Condition

To mimic a more complex ternary operator with a condition, you can combine Kotlin’s if expression with the Elvis operator.

fun checkAndReturn(obj: Any?): String {
    return if (obj is String) obj else "Not a String"
}
fun main() {
    val result = checkAndReturn("Kotlin")
    println(result)  // Output: Kotlin
    val result2 = checkAndReturn(123)
    println(result2)  // Output: Not a String
}

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

, ,

Migrating to Jetpack Compose – an interop love story

Most of you are familiar with Jetpack Compose and its benefits. If you’re able to start anew and create a Compose-only app, you’re on the right track. But this talk might not be for you…
Watch Video

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer for Jetpack Compose
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engin ...
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer f ...
Google

Jobs

Combining with a Condition

To mimic a more complex ternary operator with a condition, you can combine Kotlin’s if expression with the Elvis operator.

fun checkAndReturn(obj: Any?): String {
    return if (obj is String) obj else "Not a String"
}
fun main() {
    val result = checkAndReturn("Kotlin")
    println(result)  // Output: Kotlin
    val result2 = checkAndReturn(123)
    println(result2)  // Output: Not a String
}
Explanation
  1. Condition (if Expression):
  • The if expression checks if obj is of type String. This is similar to the condition part of the ternary operator.
  • If obj is a String, it is returned directly.
  • Otherwise, “Not a String” is returned.

2. Smart Cast:

  • When obj is of type String, smart cast allows direct access to obj as a String within the true branch of the if expression.
Full Example

Combining both smart casts and the Elvis operator provides a powerful and concise way to handle conditions and nullability in Kotlin.

fun main() {
    val obj1: Any? = "Hello"
    val obj2: Any? = null
    val obj3: Any? = 42
    val result1 = (obj1 as? String)?.length ?: -1
    val result2 = (obj2 as? String)?.length ?: -1
    val result3 = (obj3 as? String)?.length ?: -1
    println(result1)  // Output: 5
    println(result2)  // Output: -1
    println(result3)  // Output: -1
}
Summary

By using the Elvis operator (?:) and smart casts (as?), you can effectively replace the ternary operator from Java in Kotlin. This approach leverages Kotlin’s null safety and type inference features, resulting in concise and readable code.

This article is previously published on proandroiddev.com

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
Hi, today I come to you with a quick tip on how to update…
READ MORE
blog
Automation is a key point of Software Testing once it make possible to reproduce…
READ MORE
blog
Drag and Drop reordering in Recyclerview can be achieved with ItemTouchHelper (checkout implementation reference).…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu