Kotlin 2.0 was released in May 2024 and includes many change like Improved Performance, Enhanced Type Inference and Better Coroutines.
Today we’ll take a look a the new language features added.
Context Receivers
Kotlin 2.x allows you to define multiple receivers for a function
class Database {
fun queryData(): String = "Data from database"
}
class Network {
fun fetchData(): String = "Data from network"
}
context(Database, Network)
fun getData(): String {
val dbData = queryData()
val networkData = fetchData()
return "$dbData - $networkData"
}
fun main() {
val database = Database()
val network = Network()
with(database) {
with(network) {
println(getData())
}
}
}
Improved Type Inference
In Kotlin 1.x, type inference doesn’t always work.
val listOfPairs = listOf(Pair(1, "One"), Pair(2, "Two"))
val mapFromList = listOfPairs.associate { pair: Pair<Int, String> ->
pair.first to pair.second
}
In Kotlin 2.x, it does a much better job.
val listOfPairs = listOf(1 to "One", 2 to "Two")
val mapFromList = listOfPairs.associate { it.first to it.second }
Improved Coroutines
There are some small improvements to coroutines. Here’s the code in Kotlin 1.x
fun main() = runBlocking {
val deferredResults = listOf(
async { networkRequest() },
async { databaseQuery() }
)
val results = deferredResults.awaitAll()
println("Results: $results")
}
Here’s the same code for Kotlin 2.x
fun main() = runBlocking {
val results = awaitAll(
async { networkRequest() },
async { databaseQuery() }
)
println("Results: $results")
}
These are some of the changes introduced in Kotlin 2.0. Just these changes make it worth upgrading to this version.
If you have any comments or suggestions, please reach out to me on Twitter.
Photo by Jonatan Pie on Unsplash