John Bessire
John Bessire

Reputation: 571

Play scala functions return multiple items multiple times

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

Upvotes: 1

Views: 178

Answers (2)

frostmatthew
frostmatthew

Reputation: 3298

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)

Upvotes: 1

Rafa Paez
Rafa Paez

Reputation: 4860

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.

Upvotes: 1

Related Questions