// Example of if statement similar to ternary conditional operatorfunmain(){valcondition=true// Change this condition to true or falsevalans=if(condition)"yes"else"no"println("The result is "+ans)} Yields below output. In the above code, we have created a main function which is our driv...
For example, if the right side has a Boolean type, the result will be Boolean as well: val result: Boolean = if (a == b) true else false 2.2. Using when We can also use a when expression to create a pseudo-ternary operator: val result = when(a) { true -> "yes" false -> ...
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 i...
Example code: // Import the libraries in the codeimportcom.google.gson.Gson// Create a data class to define the class containing the variablesdataclassBook(valtitle:String,valauthor:String,valyear:Int)funparseJSON(jsonString:String){// Define the Gson Objectvalgson=Gson()valbook=gson.fromJson...
So, in this example the type of the variable size would be Int?. Another operator related to null-values is the elvis operator (?:). If whatever is on the left of the elvis operator is not null then the elvis operator returns whatever is on the left, otherwise it returns what is on...
In the preceding example, we use addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics. val rem = c % a The%operator is called the remainder or the modulo operator. It finds the remainder of division of one number by another. For...
. Since Kotlin became Google’s preferred language for Android development, I’ve found extension functions and explicit nullability to be the most useful features. On the other hand, when using Kotlin, the Java features that I miss the most are theprotectedkeyword and the ternary operator....
Hence, there is no ternary operator in Kotlin.Example: if block With Multiple ExpressionsIf the block of if branch contains more than one expression, the last expression is returned as the value of the block.fun main(args: Array<String>) { val a = -9 val b = -11 val max = if (a...
Note:You can ommit the curly braces{}whenifhas only one statement: Example funmain(){valtime=20valgreeting=if(time<18)"Good day."else"Good evening."println(greeting)} Try it Yourself » Tip:This example is similar to the "ternary operator" (short hand if...else) in Java....
Checking whether a given value is in a range or not usinginoperator Arangeis created using the..operator. For example, you can create a range from 1 to 10 using1..10. You’ll learn more aboutrangein a future article. Theinoperator allows you to check if a value belongs to a range/...