After having a look at the constructors in Kotlin, we now move to three useful improvements/features in Kotlin. They are quite time-saving in a long run. We also have a video tutorial:
String Template
String Template in Kotlin is a great way to concatenate two strings. In Java, it’s a pain to concatenate multiple strings. You have to close the quotes, use the +
symbol, start the quote again and then repeat this numerous times. But string template makes your life easy. Here’s how:
val marksInMaths = 56 val marksInScience = 89 val totalMarks = marksInMaths + marksInScience println("My marks in Maths are $marksInMaths while I scored $marksInScience in Science. " + "Overall my total is $totalMarks")
Notice that I just put a dollar($) sign before the variable name and it just concatenates the string. Such expression is called String Template expression. The output is:
My marks in Maths are 56 while I scored 89 in Science. Overall my total is 145
You can evaluate expressions as well using String Templates directly in the String. Example:
println("Highest marks are ${if (marksInMaths > marksInScience) marksInMaths else marksInScience}")
If you want to use a dollar sign in String instead of using it for concatenation, put forward-slash (\) before the sign to escape it.
If-Else Expression
If-Else is an expression in Kotlin which means it now returns something it’s supposed to. Here’s how you use it:
val highestMarks = if (marksInMaths > marksInScience) marksInMaths else marksInScience
As is apparent, the inequality inside the parenthesis is executed. If it evaluates to true
, the variable marksInMaths
is returned otherwise marksInScience
is returned. The returned value is then assigned to the variable highestMarks
.
If you want to execute some code along with returning value using if-else
expression, you can also do this.
val highestMarksAgain = if (marksInMaths > marksInScience) { println("The last line is returned and you can put any code here") marksInMaths } else { println("The last line is returned and you can put any code here") marksInScience }
Here you can put any code you wish to execute in the braces of if
or else
. The returning value should be put at the end of the block. That’s it!
When Expression
The switch
statement of Java is replaced by when
expression in Kotlin. It’s a more concise and elegant way to match the case and perform an appropriate action.
val totalMarks = marksInMaths + marksInScience when (totalMarks) { 100 -> println("Good score but I'm not impressed") 120 -> println("That's a great score") 140 -> { // For multiline code, use braces {} println("Well, you are really intelligent") println("You have a bright future") } else -> println("You're out of the world :)") //else is optional }
Here compiler matches its argument with all the options until the condition is satisfied. Once a branch is satisfied, the following code is executed. You can use braces ({}) for multi-line code. In the above code, when
works as a statement. Now we take a look how it works as an expression.
// When Expression returns the result and hence it can be used this way as well val totalMarksAsString = when (totalMarks) { 100 -> "Good score but I'm not impressed" 120 -> "That's a great score" 140 -> { // For multiline code, use braces {} println("If you have multiline code, the last value is assigned to the variable") "You have a bright future" //This value is gonna be assigned } else -> ("You're out of the world :)") //else is NOT optional now } println(totalMarksAsString)
Now when
is an expression in this example and it returns String
. Please note that else
block is mandatory here unless all the possible options are covered (for example, booleans or enums). If you have multiple options with same code to execute, you can combine them using a comma. For example, 100,120 ->
in above case.
To see the full code, here’s the link to my GitHub repo.
That’s it! Did you like the article? Don’t forget to provide the feedback in comments 🙂