Updated April 6, 2023
Introduction to Kotlin Ternary
The ternary is the operator, but in kotlin language, it’s not there; instead of this operator, it can be achieved using the if-else statement. It returns the value that can be according to the specific condition, which is worked exactly the same like the ternary operator if the condition itself read the code lines that can be more compatible and then the ternary so that the kotlin uses more than one if statement like nested-if, if-else-if ladder expression based on this expression. It will return the value because multiple conditions are used in the statement any of the conditions are false, it exits the loop.
Syntax
In Kotlin language has many default classes, methods, variables, operators, and other conditional statements are used to build the application. Each thing has a separate logic behind for implementing time. Like that, Ternary is the operator, but it’s not used in kotlin language; instead of that, we can achieve this by using the if-else statement itself.
fun main()
{
var variable name1:datatype;
var variable name2:datatype;
var variable name3:datatype;
if(variable name1)variable name2 else variable name3 //ternary operator used in this line now kotlin does not support this line
if variable name1 ? variable name2 : variable name3
{
----some codes which based on the above conditions----
}
else
{
---it exists the if loop and execute the else statement
}
}
The above codes are the basic syntax for implementing the ternary operator by using the if-else expression.
How does the Ternary Operator work in Kotlin?
The ternary operator is not applicable for the kotlin language generally; it works with three operands. And these operands are followed with the specific conditions that can be diagnosed with the ‘?’ operator if the expression will be executed by using the conditions that can be truthy which followed by the colon (:) operator and the final output results will be evaluated based on the expression conditional statements to execute if the condition is false. We can also use the when keyword and its also expression to validate the conditions because when it is the pseudo-ternary operator, and it is easily read and check the conditions if it’s true, it will execute the loop conditions; otherwise, it exists the loop. In that, the codes are simple, straightforward forward, and easy to read assign it for the variable values. We used another type of operator like Elvis operator to check the when and if statement conditions. Generally, the programming language uses and controls the statements to control it for the flow of the execution programs based on certain conditions. Like that ‘if ‘ is one of the conditional expressions, it has many types like if expression, if-else expression, if-else-if ladder expression, nested if expression, etc. For each type of if blocks have a different syntax, and the operators and operands are called based on the conditions.
Examples of Kotlin Ternary
Below are the different examples of Kotlin Ternary:
Example #1
Code:
sealed class Hospital
data class DSK(val id: Int) : Hospital()
data class Appolo(val id1: Int) : Hospital()
data class Hosp(val name: String, val id: Int)
infix fun <T : Any> Boolean.yes(checkcondition1: T): T? = if (this) checkcondition1 else null
infix fun <T : Any> T?.no(checkcondition2: T): T = this ?: checkcondition2
fun main() {
run {
val first = true
val out = first yes "If condition is satisfied it return true!" no "else it will return false!"
println("If the condition is satisfied it executes the loops otherwise it terminates the loop($first): $out")
}
run {
val first = false
val out = first yes "True!" no "False!"
println("If the condition is satisfied it executes the loops otherwise it terminates the loop($first): $out")
}
data class Hospdept(val name: String)
{
var patientid: Int = 0;
}
val op=Hospdept("Research & Development")
op.patientid = 41
println(op.toString());
println(op.patientid);
println("Welcome To My Domain its the first example that related to the kotlin ternary operator")
val pat = Hosp("Sivaraman", 31)
val pat1 = Hosp("Siva", 32)
val pat2 = Hosp("Raman", 29)
if (pat.equals(pat1) == true)
println("pat is still in hospital.")
else
println("pat is discharged")
if (pat.equals(pat2) == true)
println("pat is in hospital")
else
println("pat is discharged.")
println("The Hashcode of pat: ${pat.hashCode()}")
println("The Hashcode of pat1: ${pat1.hashCode()}")
println("The Hashcode of pat2: ${pat2.hashCode()}")
val id=pat.component1()
println("The Hosp id is: $id")
fun patdetails()
{
val listss:List<Hospital> = listOf(DSK(17),Appolo(2021), Appolo(2021))
println("Welcome To My Domain is the first example that related to the Kotlin ternary operator ")
val mapss = HashMap<Int, String>()
mapss.put(1, "siva")
mapss.put(2, "raman")
mapss.put(3, "arun")
mapss.put(4, "kumar")
mapss.put(5, "dhanajay kumar prasad")
mapss.put(6, "arul")
mapss.put(7, "devendran redim kumar tharun")
mapss.put(8, "daisy sran kumar yadav")
mapss.put(9, "Alan nirmal williamson")
mapss.put(10, "varadhaman vishal jain")
println(mapss)
}
val list = listOf("id", "id1", "op")
if (id !in 0..list.lastIndex) {
println("patient is died")
}
if (list.size !in list.indices) {
println("hospital total patient")
}
}
Output:
In the first example, we used some real-time examples like a hospital, the total number of patients, department details by using the if-else statement.
Example #2
Code:
fun main() {
val inpnum = -103
if(inpnum<0)
println("Thank you users the mentioned input number is negative")
else if (inpnum>0 && inpnum<10)
println("The mentioned input number is single digit so you are not entered the double and more digits")
else if (inpnum>=10 && inpnum <100)
println("You entered the input number is double digit the single and more than two digit numbers are not accepted")
else
println("The mentioned input number is three digit numbers it will not accept single, double and more than three digit numbers")
}
Output:
In the second example, we calculate the input numbers contains negative, single, multi-digit numbers by using the if-else expression.
Example #3
Code:
import java.util.Scanner
fun main(args: Array<String>) {
val inp = Scanner(System.`in`)
print("Please enter your inputs it must be the integer numbers ")
var inp1 = inp.nextInt()
var inp2 = inp.nextInt()
var inp3 = inp.nextInt()
var outp = if ( inp1 > inp2) {
if (inp1 > inp3) {
println("$inp1 is the biggest number")
}
else {
println("$inp3 is the biggest number")
}
}
else if( inp2 > inp3){
println("$inp2 is the biggest number")
}
else{
println("$inp3 is the biggest number")
}
println(outp)
}
Output:
In the final example, we used basic calculations like finding the biggest number of the series by using the if statement.
Conclusion
In kotlin, we discussed the operator like ternary, but unfortunately, kotlin does not accept this operator. Because of the if-else expression in kotlin language if, while are the conditional expression so it will manage the operands based on the conditions. So ternary is not applicable and not useable for the programmer.
Recommended Articles
This is a Guide to Kotlin Ternary. Here we discuss the introduction, syntax, and working of Ternary in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –