Reputation: 3
I have a ListMap
with Tuple4
as values:
val dbCons = ListMap (
"con1" -> ("str 1", "str 2", "str 3", true)
// etc.
)
/*line A*/def testAllCon(map: ListMap[String, Tuple4[String,String, String, Boolean]]): Unit = {
map.keySet.foreach{ key =>
val prop = map.get(key).get
/*line B*/val dbSchema = DbSchema(prop._1, prop._2, prop._3, prop._4)
}
How do I make declaration at "Line A" and, if possible, its usage at "Line B," less verbose.
I checked a similar question here, please direct.
Upvotes: 0
Views: 63
Reputation: 51271
As @JackLeow has pointed out, you can use a type alias to create a shorter reference for the tuple.
The testAllCon()
method can also be shortened like so.
def testAllCon(map: ListMap[String, Record]): Unit =
map.values.foreach{ prop =>
val dbSchema = DbSchema.apply _ tupled prop
}
Upvotes: 1
Reputation: 22487
You could define a type alias
for the 4-tuple. I'm calling it Record
in my example here, but you'd probably want to give it a more descriptive name.
Also, for "line B", you can define the function as a pattern-match:
type Record = (String, String, String, Boolean)
val dbCons = ListMap (
"con1" -> ("str 1", "str 2", "str 3", true)
// etc.
)
// With the for-comprehension syntax
/*line A*/def testAllCon(map: ListMap[String, Record]): Unit = {
for ((key, (s1, s2, s3, b)) <- map) {
/*line B*/val dbSchema = DbSchema(s1, s2, s3, b)
}
}
// Without for-comprehension syntax
/*line A*/def testAllCon(map: ListMap[String, Record]): Unit = {
map.foreach {
case (key, (s1, s2, s3, b)) =>
/*line B*/val dbSchema = DbSchema(s1, s2, s3, b)
}
}
Upvotes: 1