This is the sixth part of the video series on Kotlin language.
Read and watch the other parts here.
1. | Hello Kotlin |
2. | Declaring Variables |
3. | Data Types |
4. | String (Part 1) |
5. | String (Part 2) |
In this video, we discuss conditional expressions. Yes, it’s conditional expressions and not just conditional statements.
Let’s write a pretty simple if-else condition.
fun main(args:Array<String>){ val comment:String if(age > 50) comment = "Getting old" else comment = "You'll get there" println(comment) }
if-else conditions can be written as expressions in Kotlin. And that, eliminates the need for having a ternary operator.
//if-else used as an Expression val anotherComment = if(age > 50){ "Getting Old" } else{ "You'll get there" } println(anotherComment) //Even better val finalComment = if(age > 50) "Getting Old" else "You'll get there" println(finalComment)
The finalComment variable above just resembles our ternary operator. It’s pretty cool.
switch-case statements are available as when statements in Kotlin.
val age = 52 val comment:String when(age) { 50 -> comment = "Half century" 25 -> comment = "Young" else -> comment = "Hmm" } println(comment) val anotherComment:String when { age > 50 -> anotherComment = "Getting old" else -> anotherComment = "You'll get there" } println(anotherComment)
The when statements can also be written as expressions like this.
//As an expression val finalComment = when { age > 50 -> "Getting Old" else -> "You'll get there" } println(finalComment)
You can find the video here.