Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to give `x._1._2` parameters actual names

Tags:

scala

Is there a way to name parameters .map function takes? See the following in Scala example:

aggregated.map( (kv: ((String, Int, Int), (Int, Int))) =>("some stuff"))

I would like to name them like

aggregated.map( (kv: ((name:String, score:Int, anInt:Int), (age:Int, count:Int))) =>("some stuff"))

This would make it easier to refer to the params when the mapping is done. For example instead of using kv._1._2 I could say score or kv.score. Makes code more readable and easier to debug.

like image 885
Adrian Avatar asked Feb 21 '14 20:02

Adrian


2 Answers

use "case" to extract variables from tuples using pattern matching:

aggregated.map { case((name, score, anInt), (age,count)) => ... }

you do not need to specify type annotations, the type inferencer does that for you:

    scala> List((("a",true,2),(1.0,2L)), (("b",false,11),(2.0,3L))).map { 
       case ((a,b,c),(d,e)) => s"$a$b$c$d$e" 
    }
    res3: List[String] = List(atrue21.02, bfalse112.03)
like image 188
Giovanni Caporaletti Avatar answered Oct 30 '22 12:10

Giovanni Caporaletti


The usual answer is to decompose with a pattern matching anonymous function, as the other answer says, but this one also just occurred to me:

scala> List((("a",true,2),(1.0,2L)), (("b",false,11),(2.0,3L))).map { kv =>
     | import kv._1.{_1 => s}
     | s
     | }
res1: List[String] = List(a, b)

That's fewer byte codes than the pattern match if you're not extracting all the fields.

scala> List((("a",true,2),(1.0,2L)), (("b",false,11),(2.0,3L))).map {
     | case ((s,_,_),_) => s
     | }
res2: List[String] = List(a, b)
like image 2
som-snytt Avatar answered Oct 30 '22 12:10

som-snytt