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
- Safe Cast (
as?
):
obj as? String
attempts to castobj
to aString
. If the cast is not possible, it returnsnull
instead of throwing aClassCastException
.
2. Smart Cast with Elvis Operator (?:
):
(obj as? String)?.length
safely calls thelength
property ifobj
is successfully cast to aString
. Ifobj
is not aString
, the expression evaluates tonull
.- The Elvis operator
?:
then provides a fallback value-1
if the left-hand side expression isnull
.
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
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
- Condition (
if
Expression):
- The
if
expression checks ifobj
is of typeString
. This is similar to the condition part of the ternary operator. - If
obj
is aString
, it is returned directly. - Otherwise, “Not a String” is returned.
2. Smart Cast:
- When
obj
is of typeString
, smart cast allows direct access toobj
as aString
within the true branch of theif
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