This simple trick will have you creating multiple returns in Kotlin.

Dai
AndroidPub
Published in
2 min readMay 22, 2017

--

Some languages, such as Go, allow for multiple returns. In Go its commonly used to return an error or the expected result.

In Kotlin we don’t necessarily have multiple returns, but we can achieve the same result using destructuring.

Destructuring

Destructuing is a way of breaking down an object properties into individual variables. For example, lets say we have a normal data class with 3 properties

In the example above you can see we have created a simple Car data class and used parenthesis to pull out the properties and assign them to individual values. This is destructuring.

val (make, _, model) = car1

We can also ignore values we do not care about by using an underscore.

At this point you may have already figured out where we are going with this..

The Main Event: Multiple Returns

To achieve multiple returns in Kotlin all we need to do is destructure something like a Result data class. On this data class we can add two properties, lets say something like our Go example at the top of this post, result and error. For the purpose of this example I am going to just use String for the result and error types but you can use whatever you want really.

Working from the top, we define a data class with result and error as the two properties. I have made error optional and set its default to null, but you should do whatever makes more sense for your use case.

We then define a function that returns our Result data class after doing some task. This could be anything that could potentially fail and return an error or succeed and return the intended result.

The last line is where the multiple return finally takes shape. We use the Result returned from the function and desctructure the properties to give us both a result and err value returned from the same function.

There you go. Multiple Returns in Kotlin.

--

--

Dai
AndroidPub

Engineering Manager (Client Platforms) @Plex