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.
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)
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)
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