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?
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
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With