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.

In Java, the ternary operator looks like this:

String result = (condition) ? "True value" : "False value";

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

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
}

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.

Source link