Search code snippets, questions, articles...

Use Ternary Operator in Kotlin

Ternary operators in any programming language are used to write conditional statements in one line. In this post, we are going to explain how you can use if else condition in one line using Kotlin.
val v = 9

val result = if (v > 10) "Greater than 10" else "less than 10"

println(result)

Output

Less than 10

We can write conditional statements in one line as shown in the above code example. Here, we have created a variable named v and assigned a value to it. We are assigning value to variable named result based on some conditions. If v is greater than 10 it(result) will be assigned "Greater than 10" value else it will be assigned "Less than 10" value.

Syntax

if (condition) a else b

Code example 2

val isUser = true

val userRole = if (isUser) "user" else "ext"

print(userRole)

Output

user
Was this helpful?
0 Comments
Programming Feeds
Learn something new everyday on Devsheet