Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top