Variable names in Kotlin when expressions

Nick Lydon
1 min readDec 1, 2021

--

Recently I’ve been learning Kotlin and I wanted to reproduce something that I use quite often in C#.

The switch expression in C# gets more powerful with each release. One of the patterns is to pattern match on an expression, and assign the value to a local variable. Here’s an example:

Breaking it down — we have some record classes that are making up a sum type. We have a choice between a StringToken or a BoolToken. To unwrap the value, we use a switch expression, with separate cases for each concrete type. When we match on the concrete type we give it a variable name to be used in the expression on the right hand side (st and bt).

This is quite concise, because there’s no need to assign a temporary variable outside of the expression. I wanted to do something similar in Kotlin, but couldn’t immediately see how:

The syntax is very similar between the two languages. The difference is where I’ve added the ?? to show that there’s no variable associated with the pattern-matched types. I’ve found the solution by using val token = getToken() as the expression supplied to when:

This is quite nice, because Kotlin will infer the type of token within each expression, there’s no need to define it more than once! Similar to C#, the variable is correctly scoped only to the when expression, so won’t be available outside it.

--

--

Nick Lydon
Nick Lydon

Written by Nick Lydon

British software developer working as a freelancer in Berlin. Mainly dotnet, but happy to try new things! https://github.com/NickLydon

No responses yet