Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala equivalent to Python returning multiple items

Tags:

python

scala

In Python it's possible to do something like this:

def blarg():
    return "blargidy", "blarg"

i, j = blargh()

Is there something similar available in scala?

like image 900
dave Avatar asked Dec 20 '11 19:12

dave


2 Answers

You can return a tuple:

def blarg = ("blargidy", "blarg")

val (i, j) = blarg

Note the pattern-matching syntax for parallel variable assignment: this works for any pattern, not just for tuples. So for instance:

val list = 1 :: 2 :: 3 :: Nil

val x :: y = list // x = 1 and y = 2 :: 3 :: Nil
like image 150
Philippe Avatar answered Oct 17 '22 09:10

Philippe


I realize this is an old question, but there's another way to achieve the same. I don't know if there's any downside to it, but the advantage is that the values returned are "named", making the code a little more self-explanatory.

(tested on scala 2.11)

package test.scala.misc

object TestReturnMultipleNamedValues extends App {

    val s = getMultipleNamedValues

    println(s"changed=${s.dsChanged} level=${s.dsLevel}")

    /** Returns an anonymous structure with named members.
     * */
    def getMultipleNamedValues() : {val dsChanged : Boolean;val dsLevel : Int} = {
        new {
            val dsChanged = true
            val dsLevel = 1
        }
    }
}
like image 35
slaursen Avatar answered Oct 17 '22 11:10

slaursen