What’s New in Kotlin 1.3
This article will take you through the advancements and changes the language has to offer in its latest version. By Joey deVilla.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Kotlin has come a long way since its initial release in July 2011. It was originally designed as a replacement for Java to be used by JetBrains’ programmers, who were frustrated by Java’s limitations and found that their preferred language, Scala, compiled too slowly. Since then, it has grown from an interesting side project, used by a handful of developers, to the Google-decreed preferred language for Android development.
Kotlin is making inroads into other platforms, with the the Kotlin-to-JavaScript transpiler for web development and Kotlin/Native, which aims to compile Kotlin into native applications that run on iOS, MacOS, Windows, Linux and WebAssembly.
It’s also making inroads into developers’ hearts and minds. HackerRank’s 2019 Developer Skills Report, based on their survey with over 70,000 participants, lists Kotlin as one of the top 3 programming languages that developers want to learn in 2019.
Kotlin 1.3 has been around since October 2018, but that doesn’t mean that it’s too late to take a closer look at the features that this latest version brings. Kotlin is still new to many developers, even those who develop Android apps for a living.
In this tutorial, you’ll learn about the most important changes in Kotlin 1.3.
The Kotlin Playground
One of the most useful recent programming trends is the playground. An interactive environment that lets you enter and then run snippets of code and see the results without having to set up a whole new project. They’re useful for learning a new language or framework and for answering “What if I tried this?” questions.
It’s a simplified online IDE that lets you enter Kotlin code, execute it and even share it by providing a link to your code, or as an embedded iframe that you can include on a web site.
Let’s try out the Kotlin Playground. Point your favorite browser at play.kotlinlang.org. You’ll be taken to a web page that looks like this:
Click the Run button to run the sample code that was provided by the Kotlin Playground. An output pane with the text Hello, world!!!
will appear at the bottom of the page.
Before continuing, click the Settings button. This pop-up will appear:
This lets you select which version of Kotlin will be used when you click the Run button. Select the latest 1.3 version in the Kotlin Version menu. At the time of writing, it’s 1.3.40.
Now that you’ve got the playground set up, it’s time to try out some Kotlin 1.3 features!
Language Improvements
Main Function Without Arguments
Every program has an entry point when the program is executed. Thanks to the influence of C, the entry point for programs in many programming languages is called main()
. It’s in every Kotlin program, even in an Android Studio project.
Another C convention borrowed by Kotlin is that main()
takes an array of strings as its argument. This array contains the parameters that follow the program’s name when it’s run from the command line.
Until Kotlin 1.3, this was the only version of the main()
function in Kotlin, and you’d have to write Hello, World! programs like this:
fun main(args: Array<String>) {
println("Salutations, user!")
}
The single argument, args
, contains the arguments that’re passed to the Kotlin program when it’s called from the command line.
In Kotlin 1.3, you’d simply ignore args
. You can use a new form of main()
that doesn’t take any arguments at all. This is useful for applications where you don’t expect command line parameters, including those you’d write in the Kotlin playground.
Run the following in the Kotlin Playground:
fun main() {
println("Salutations, user!")
}
It works as you’d expect, without arguments.
Subject Capture
The Kotlin 1.3 improvement you’re most likely to use is the when
keyword new subject capture capability.
Consider the following:
fun fastCheapOrGood(): String {
return when (determineOutcome()) {
0 -> "Fast."
1 -> "Cheap."
2 -> "Good."
else -> "None of the standard outcomes."
}
}
The subject is the value that comes after the when
keyword. In the function above, the subject is determineOutcome()
, and its value determines which of when
’s cases is applied.
Suppose you wanted to display determineOutcome()
value in the else
case. In Kotlin 1.3, there was no way to “capture” when
’s subject. The usual solution is to declare an extra variable like so:
val outcome = determineOutcome()
return when (outcome) {
0 -> "Fast."
1 -> "Cheap."
2 -> "Good."
else -> "None of the standard outcomes: the selection was $outcome."
}
This works, but it introduces two complications:
- It introduces a new variable whose scope exists outside the
when
block. This is fine if you want to use outcome beyond the scope ofwhen
, but introduces the risk of side effects if you don’t need the value of outcome anywhere else. - It adds an extra line of code. That may not seem like such a bad thing, but consider Corbato’s Law : “Every programmer has a number of lines of code they can write in a day, and this number’s the same, no matter the programming language.” The take-away from this is that you should program in languages and ways that let you do as much as possible, with as little code as possible.
This is where Kotlin 1.3’s new subject capture for when
comes in. It allows you to declare a variable that captures when
’s subject, and whose scope is limited to the when
block:
return when (val outcome = determineOutcome()) {
0 -> "Fast."
1 -> "Cheap."
2 -> "Good."
else -> "None of the standard outcomes: the selection was $outcome."
}
Now, there’s one less line of code and one less stray variable.
Random Number
If you needed a random number generator for a desktop or mobile Kotlin project, you could always rely on the Java Virtual Machine’s Random class. But, with Kotlin expanding beyond Android and other Java-based systems, there needed to be a Kotlin-specific way to generate random numbers that works across platforms.
The solution is an abstract class that can implement any number of randomizing algorithms. If you don’t need a cryptographically secure random number generator, the default implementation provided by the Random.Default
companion object should suit most needs.
Let’s take Kotlin’s Random for a spin. Run the following in the Kotlin playground a few times:
import kotlin.random.*
fun main() {
println("${fastCheapOrGood()}")
}
fun fastCheapOrGood(): String {
return when (determineOutcome()) {
0 -> "Fast."
1 -> "Cheap."
2 -> "Good."
else -> "None of the standard outcomes."
}
}
fun determineOutcome(): Int {
return Random.nextInt(6) // Generates a random number between 0 and 5 inclusive.
}
Random comes with many extension functions that save you from having to use an extra line to declare an index variable to pick a random item from an array or collection. Run this in the Kotlin Playground:
import kotlin.random.*
fun main() {
val colors = arrayOf("amaranth", "coquelicot", "smaragdine")
println("Random array element: ${colors.random()}")
val flavors = listOf("maple", "bacon", "lemon curry")
println("Random list item: ${flavors.random()}")
}
There’re also extension functions that you can use to pick a random character from a string or a random item from a range. Add the following to the end of main()
and run the code again:
val pangram = "How razorback-jumping frogs can level six piqued gymnasts!"
println("${pangram.random()}")
val firstHalfOfAlphabet = 'a' .. 'l'
println("Random range item: ${firstHalfOfAlphabet.random()}")