Reputation: 455
I'm trying to create an informative report according to results. I currently have a .foreach loop iterating over a list, and writes the report.
The code looks like:
result.foreach {
tupleResult =>
tupleResult._3 match {
case "FirstTest" =>
language1 = createReport(tupleResult)
case "SecondTest" =>
language2 = createReport(tupleResult)
case "ThirdTest" =>
language3 = createReport(tupleResult)
}
finalReport = ""
}
Each "createReport" is a method which creates a one line String into the relevant language var. I want each iteration to add a different line in the "finalReport" string.
Example of "finalReport":
Report consists of the following:
1) language1
2) language2
3) language3
The question is how to create the different variables as different lines of the same "finalReport" string.
Upvotes: 0
Views: 223
Reputation: 20415
Associating an ordering to the test strings may prove a solution, for instance like this,
val ord = Array("FirstTest","SecondTest","ThirdTest").zipWithIndex.toMap
Then we can generate the parts of the report, and finally sort them by the defined ordering,
val finalReport = result.map { tRes => (ord.get(tRes._3), createReport(tRes)) }
.sortBy(_._1)
.map(_._2)
.mkString("\n")
Upvotes: 1
Reputation: 11479
The more idiomatic scala way to do it would be to not do several things at once and also mutate state, but instead see it as separate operations/expressions. Something like this for example:
val sortedResults = result.sortBy(_._3 match {
case "FirstTest" => 1
case "SecondTest" => 2
case "ThirdTest" => 3
})
val reportLines = sortedResults.map(result => createReport(result._3))
val finalReport = reportLines.mkString("\n")
Upvotes: 2