Home > Back-end >  Assigning Pairs to Already Defined Vars in Kotlin
Assigning Pairs to Already Defined Vars in Kotlin

Time:10-02

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.

I would appreciate any advice since this would be really useful and I have yet to find a way to do it.

CodePudding user response:

Unfortunately that's not allowed as far as I know. The current Kotlin syntax allows for destructuring declarations, but that only works if you declare the variables at that time. In your example you declared the variables above and just want to assign a value.

Looking at the grammar makes it clear that assignment only accepts a directlyAssignableExpression (such as a simpleIdentifier). A declaration instead accepts a multiVariableDeclaration.

CodePudding user response:

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 }
  • Related