Allen Nie Allen Nie - 3 months ago 9
Scala Question

What is is "(x, y)" in Scala, and what is actually being returned?

scala> def check(a: Int, b: Int): (Int, Int) = {
(3, 4)
}


The returning type is
(Int, Int)
. How is this possible? What is Scala actually returning? A tuple? An array? What is this type anyway?

I know I can then call this function like this:

scala> val (a, b) = check(1,2)
a: Int = 3
b: Int = 4


Or this:

scala> val x = check(1,2)
x: (Int, Int) = (3,4)


I'm still learning Scala, but I can't recall if I have seen this before or not, or the name of this syntax. What is it?

The first example I gave is rather easy, returning
(3, 4)
. Is there a more realistic way of returning this
(Int, Int)
type? Must I always put the final result (let's assume x and y values contain the final output of these two inputs) like this
(x, y)
or return
(x, y)
?

Answer

As @dhg mentioned, (Int, Int) is equals to Tuple2[Int, Int]

In second sample you use pattern matching in variable definition. You can use it with tuples, case classes and with everything which has extractors. Actually, everything works via extractors.

scala> val p = Point(1, 2)
p: Point = Point(1,2)

scala> val Point(x, y) = p
x: Int = 1
y: Int = 2

scala> val Property = "(.+)=(.+)".r
Property: scala.util.matching.Regex = (.+)=(.+)

scala> val Property(name, value) = "name1=value1"
name: String = name1
value: String = value1