In Scala, what does x=> x._1._1 denotes

Viewed 4608

In the following snippet of code, I am aware that x._1 denotes the first element of the tuple, but I couldn't understand what x._1._1 represents.I am not so familiar with Scala, sorry if it is a relatively naive question, thank you!!

val a = b.groupBy(x=> x._1._1)
3 Answers

Here is a quick example in the REPL of a nested tuple

scala> val t = ((1, 2), 3)
t: ((Int, Int), Int) = ((1,2),3) 

scala> t._1  // Get the first part of the tuple
res0: (Int, Int) = (1,2)

scala> t._2  // Get the second part of the tuple
res1: Int = 3

scala> t._1._1  // Get the first part of the first part
res2: Int = 1 

And here is an example with a sequence to demonstrate the groupBy:

scala> val s = Seq(((1, 2), 3), ((1, 5), 6), ((2, 4), 32))
s: Seq[((Int, Int), Int)] = List(((1,2),3), ((1,5),6), ((2,4),32))

scala> s.groupBy
   def groupBy[K](f: (((Int, Int), Int)) => K): scala.collection.immutable.Map[K,Seq[((Int, Int), Int)]]

scala> s.groupBy(x => x._1._1)
res3: scala.collection.immutable.Map[Int,Seq[((Int, Int), Int)]] = Map(2 -> List(((2,4),32)), 1 -> List(((1,2),3), ((1,5),6)))

In this case the first element of the first element are the target for the grouping. Here's the result in an easier to look at format:

Map(
  2 -> List(
    ((2,4),32)), 
  1 -> List(
    ((1,2),3),
    ((1,5),6))
  )

It means x._1 itself is a tuple. Example:

val b = Seq((("subTuple_1", "subTuple_2"), "tuple_2"))
val a = b.groupBy(x=> x._1._1)

As you mentioned ._1 gives you the first column of your tuple, and if the result of first column is Tuple, you can do ._1.

eg.

scala> Map(("a" -> "b") -> 100, ("c" -> "d") -> 200).map(_._1)
res31: scala.collection.immutable.Map[String,String] = Map(a -> b, c -> d)

scala> Map(("a" -> "b") -> 100, ("c" -> "d") -> 200).map(_._1._1)
res32: scala.collection.immutable.Iterable[String] = List(a, c)

groupBy,

scala> Map(("a" -> "b") -> 100, ("a" -> "c") -> 200).groupBy(_._1._1)
res19: scala.collection.immutable.Map[String,scala.collection.immutable.Map[(String, String),Int]] = Map(a -> Map((a,b) -> 100, (a,c) -> 200))
Related