1

I have a function that returns Long and a Json object which I would like to call multiple times using the same variable names.

def returnMultipleItems (): (Long, JsObject) = {

    val number:Long = 123

    val json = Json.obj(
        "Name" -> "Tom",
        "age" -> 42
    )

    return(number, json)
}

When calling the function like this it works fine.

var (number, json) = returnMultipleItems    
println("Number = " + number, ", Json = " + json)

I would like to call the function two or more times using the same variable names. With this I get error messages like ";" is expected but "=" is found.

var number:Long = 0
var json:JsObject = Json.obj()

(number, json) = returnMultipleItems // Call the function

(number, json) = returnMultipleItems // Call the function again
John Bessire
  • 571
  • 5
  • 20

2 Answers2

1

Scala does not accept multiple variable assigment. However, your first example works because Scala interprets the form var (x, y) = (1, 2) as pattern matching.

A full explanation is here and workarounds are here.

Community
  • 1
  • 1
Rafa Paez
  • 4,820
  • 18
  • 35
1

May not be exactly what you're looking for but you could assign the variable to the tuple (instead of the contents) e.g.

var numJson = returnMultipleItems
println("Number = " + numJson._1, ", Json = " + numJson._2)
numJson = returnMultipleItems
println("Number = " + numJson._1, ", Json = " + numJson._2)
frostmatthew
  • 3,260
  • 4
  • 40
  • 50