How to return two values in Kotlin?

Viewed 2475

I currently return liveDataName, but I also want to return liveDataImage.

fun getProfileInfo(): LiveData<String> {

        val call: Call<UserProfile>? = NetworkService.getInstance()
                .jsonApi
                .getProfile()
        call?.enqueue(object : Callback<UserProfile>{
            override fun onResponse(call: Call<UserProfile>, response: Response<UserProfile>) {
                if (response.isSuccessful) {
                    response.body()?.let {
                        liveDataName.value = it.username
                        liveDataImage.value = it.defaultAvatar
                    }
                }

            }

            override fun onFailure(call: Call<UserProfile>, t: Throwable) {}
        })

        return liveDataName
    }
3 Answers

You could return a Pair:

fun getProfileInfo(): Pair<LiveData<String>, LiveData<String>> {
  // ...
  return Pair(liveDataName, liveDataImage)
}

Most of the time, when wanting to return multiple values it is the best to create a new class for that purpose. For example:

data class NameAndImage(val name: String, val image: String)

And then you could simply return NameAndImage from your function

fun getProfileInfo(): LiveData<NameAndImage> {
    return NameAndImage(liveDataName, liveDataImage)
}

To my mind, this is better than returning a Pair or a list, because you 100% know where which value is. You could just easily do nameAndImage.name which is better than pair.data.first where you have to think again what first was..

Kotlin Pair/Triple class.

Kotlin has generic Pair and Triple types that can be used to return two or three values from the function. Note that it’s preferred to have your data named properly and a data class should be used to return more values.

fun fetchPersonDetails(): Triple<String, Int, Char> {
   val name = "Riya"
   val age = 18
   val gender = 'M'

   return Triple(name, age, gender)
}

fun main() {
   val (name: String, age: Int, gender: String) = fetchPersonDetails()

   println("($name, $age, $gender)")        // (Riya, 18, M)
}
Related