Search code examples
functionkotlinvar

Assigning Pairs to Already Defined Vars in Kotlin


I'm trying to return a pair from a function and assign it to already defined variables, in Kotlin.
The way I've seen pairs received from a function until now is:

val/var (thing1, thing2) = FunctionReturningPair()

Is it possible to assign already defined variables to the pair? Something like:

var thing1: String
var thing2:int
//do other things here
(thing1, thing2) = FunctionReturningPair() 
//note that thing1 and thing2 were ALREADY DEFINED.

Solution

  • I don't see a reason of why that would not work, but apparently it does not. In the docs, I don't see any mention of doing that as well. Usually features are added if there is a consensus that 1. people consider that they are needed. And 2. they are not going to break other things / or be confusing. So I guess that one of those conditions has not been met, or nobody ask for it.

    If you really want it, it might be worth checking youtrack to see if somebody else requested it. If they have vote for it, and if not, write a feature request.

    Until then, I guess that you are stuck with one of these ways:

    val p = functionReturningPair()
    thing1 = p.first
    thing2 = p.second
    

    OR

    functionReturningPair().let { (first, second) -> thing1 = first; thing2 = second }