How to Return Two Values In Kotlin?

10 minutes read

In Kotlin, it is not possible to directly return two values from a function like in some programming languages. However, there are a few different approaches to achieve the same result:

  1. Using Pairs: Kotlin provides the Pair class to hold two values. You can create a Pair object and return it from the function. Here is an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fun returnTwoValues(): Pair<Int, String> {
    val value1 = 10
    val value2 = "Hello"
    return Pair(value1, value2)
}

fun main() {
    val result = returnTwoValues()
    val value1 = result.first
    val value2 = result.second
    println("Value 1: $value1")
    println("Value 2: $value2")
}


  1. Using Data Classes: Kotlin allows you to create data classes that hold multiple properties. You can create a data class with two properties and return an object of that class. Here is an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
data class TwoValues(val value1: Int, val value2: String)

fun returnTwoValues(): TwoValues {
    val value1 = 10
    val value2 = "Hello"
    return TwoValues(value1, value2)
}

fun main() {
    val result = returnTwoValues()
    val value1 = result.value1
    val value2 = result.value2
    println("Value 1: $value1")
    println("Value 2: $value2")
}


These are two common techniques to return multiple values in Kotlin. You can choose the one that suits your requirements the best.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Java to Kotlin: A Refactoring Guidebook

Rating is 4.8 out of 5

Java to Kotlin: A Refactoring Guidebook

4
Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

Rating is 4.7 out of 5

Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

5
Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

Rating is 4.6 out of 5

Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

6
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.5 out of 5

Kotlin Cookbook: A Problem-Focused Approach

7
Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

Rating is 4.4 out of 5

Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

8
Kotlin and Android Development featuring Jetpack: Build Better, Safer Android Apps

Rating is 4.3 out of 5

Kotlin and Android Development featuring Jetpack: Build Better, Safer Android Apps


How to handle version compatibility when returning multiple values in Kotlin?

When returning multiple values in Kotlin, you can use either data classes or tuples. However, there might be version compatibility concerns when returning multiple values, especially if you are using versions of Kotlin before 1.2.


Here are a few approaches to handle version compatibility when returning multiple values in Kotlin:

  1. Using data classes: Declare a data class with properties representing the multiple values you want to return. Ensure that your version of Kotlin supports data classes (Kotlin 1.1 and above). For older versions of Kotlin, you can create a custom class with properties and appropriate constructors, getters, and setters.


Example:

1
2
3
4
5
6
7
8
data class Result(val value1: String, val value2: Int)

fun performOperation(): Result {
    // perform some operation
    val value1 = "hello"
    val value2 = 10
    return Result(value1, value2)
}


  1. Using tuples: Before Kotlin 1.2, there is no built-in support for tuples. However, you can use libraries like kotlinx.serialization or Arrow to achieve tuple-like behavior. If you are using Kotlin 1.2 or higher, you can leverage destructuring declarations to handle returning multiple values as tuples.


Example with kotlinx.serialization:

1
2
3
4
5
6
7
8
import kotlinx.serialization.Pair

fun performOperation(): Pair<String, Int> {
    // perform some operation
    val value1 = "hello"
    val value2 = 10
    return Pair(value1, value2)
}


Example with destructuring declarations:

1
2
3
4
5
6
fun performOperation(): Pair<String, Int> {
    // perform some operation
    val value1 = "hello"
    val value2 = 10
    return value1 to value2
}


Using the appropriate approach based on your Kotlin version will ensure compatibility while returning multiple values.


How to create a custom data type to return multiple values in Kotlin?

In Kotlin, you can create a custom data type to return multiple values using either a data class or a class with multiple properties. Here are the step-by-step instructions for both approaches:

  1. Data Class Approach: To create a data class to hold multiple values, follow these steps:


Step 1: Define a data class with the desired properties that represent the values you want to return.

1
data class MyCustomDataType(val value1: Int, val value2: String, val value3: Boolean)


Step 2: Initialize an instance of the data class with the values you want to return and utilize it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
fun myFunction(): MyCustomDataType {
    val value1 = 42
    val value2 = "Hello, World!"
    val value3 = true
    
    return MyCustomDataType(value1, value2, value3)
}

fun main() {
    val result = myFunction()
    println(result) // Output: MyCustomDataType(value1=42, value2=Hello, World!, value3=true)
    println(result.value1) // Output: 42
    println(result.value2) // Output: Hello, World!
    println(result.value3) // Output: true
}


  1. Class with Multiple Properties Approach: To create a class with multiple properties to hold the return values, follow these steps:


Step 1: Define a class with the desired properties that represent the values you want to return.

1
class MyCustomDataType(val value1: Int, val value2: String, val value3: Boolean)


Step 2: Initialize an instance of the class with the values you want to return and utilize it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
fun myFunction(): MyCustomDataType {
    val value1 = 42
    val value2 = "Hello, World!"
    val value3 = true
    
    return MyCustomDataType(value1, value2, value3)
}

fun main() {
    val result = myFunction()
    println(result) // Output: MyCustomDataType@4f023edb
    println(result.value1) // Output: 42
    println(result.value2) // Output: Hello, World!
    println(result.value3) // Output: true
}


Note: When printing the instance of the class, you may see a hashcode value (e.g., MyCustomDataType@4f023edb). If you want to print meaningful representations, you can override the toString() method in the class.


Both approaches are valid options, and you can choose the one that suits your specific requirements and coding style.


What are the alternatives to returning two values in Kotlin?

There are several alternative approaches to returning multiple values in Kotlin:

  1. Data classes: You can create a data class to encapsulate multiple values and return an instance of that class. This allows you to easily return multiple values as a single object.
1
2
3
4
5
6
7
data class Person(val name: String, val age: Int)

fun getPerson(): Person {
    val name = "John"
    val age = 25
    return Person(name, age)
}


  1. Pair / Triple classes: Kotlin provides Pair and Triple classes to represent two or three values, respectively. You can use these classes to group multiple values and return them together.
1
2
3
4
5
fun getPerson(): Pair<String, Int> {
    val name = "John"
    val age = 25
    return Pair(name, age)
}


  1. Map: You can use a Map to associate values with keys and return the map as a result. This allows you to return multiple values with labels that can be accessed using keys.
1
2
3
4
5
6
7
fun getPerson(): Map<String, Any> {
    val person = mapOf(
        "name" to "John",
        "age" to 25
    )
    return person
}


  1. Custom classes: You can create your own custom classes to represent multiple values specific to your use case. This allows you to define the structure and behavior of the returned values in a way that best suits your needs.
1
2
3
4
5
6
7
class PersonWithAddress(val person: Person, val address: String)

fun getPersonWithAddress(): PersonWithAddress {
    val person = Person("John", 25)
    val address = "123 Main St"
    return PersonWithAddress(person, address)
}


Each of these alternatives provides a different approach to returning multiple values in Kotlin, and the choice depends on the specific requirements and structure of your code.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To switch between multiple versions of Kotlin, you can follow these steps:Open your Kotlin project in your desired integrated development environment (IDE). Locate the build.gradle file in your project&#39;s root directory. Inside the build.gradle file, find t...
To check if a server is reachable using Retrofit in Kotlin, you can follow the steps below:Import the necessary dependencies in your Kotlin project. This includes the Retrofit library and the required network permission in your AndroidManifest.xml file: implem...
To test a private function in Kotlin, you can follow these steps:Import the necessary testing dependencies: Depending on your build tool, you need to add the appropriate testing framework in your project, such as JUnit or KotlinTest. Create a new test class: C...