3

Given this Scala function

def mv: (Int,Int,Int) = {
  (1,2,3)
}

The following works

val (i,j,k) = mv

But this does not

var i = 0
var j = 0
var k = 0
(i,j,k) = mv
<console>:1: error: ';' expected but '=' found.
   (i,j,k) = mv
           ^

This implies that assigning to multiple variables only works when they are initialized? or maybe I'm writing it incorrectly? Trying to find a way to return several values from a function and assign the values to instance variables in a Class, which means the variables can't be initialized when the function is called because they are declared outside of all methods.

class C {
  var i = 0
  var j = 0
  var k = 0
  def mv: (Int,Int,Int) = {
    (1,2,3)
  }
  def changeState: Unit = {
    (i,j,k) = mv
  }
}

The above does not work. I could create a case class to hold the return values but would like to make something this work since it seems more clear.

1
  • Please note update following comments on initial proposal. Commented May 11, 2014 at 14:11

1 Answer 1

1

I found a way to make it work but it seems wrong minded:

class C {
  var i = 0
  var j = 0
  var k = 0
  def mv: (Int,Int,Int) = {
    (1,2,3)
  }
  def changeState: Unit = {
    val (x,y,z) = mv
    i = x
    j = y
    k = z
  }
}

val c = new C
c.i == 0 //true
c.changeState
c.i == 1 //true so this works

So it works but is ugly

Sign up to request clarification or add additional context in comments.

2 Comments

This is the best solution, anyway. Scala does not support multiple assignment (ScalaReference section 6.15). See stackoverflow.com/questions/3348751/… and stackoverflow.com/questions/2776651/scala-tuple-deconstruction @user3189923 's answer is misguiding.
Yeah, too bad but true. Scala implicitly determines what to do and so hides what is really happening sometimes. That's nice usually, it leads to less verbose code, but it also can obscure problems. The multivalued return is really a hidden Tupple3[Int,Int,Int] I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.