I'm working on this scala code:
case class M(a: String, b: Int) val mm1 = List(Map("a" -> "001", "b" -> 12), Map("a" -> "002", "b" -> 25), Map("a" -> "003", "b" -> 100)) val mm2 = List(M("001", 12), M("004", 99), M("003", 100)) def validate(mm1: List[Map[String, Any]], mm2: List[M]): Boolean = { for (m1 <- mm1) { var found = false val a = m1("a") // nested loop: iterate mm2 breakable { for (m2 <- mm2) { if (a == m2.a) { assert(m1("b") == m2.b) found = true break // if found just break } } } // All of elements in mm1 must exist in mm2. // We will know this if "found" variable is set to true. assert(found == true) } true } Basically the validate method just make sure all of value in mm1 exist in mm2 (based on "text" key/property), the other way around is not necessary. Then it also make sure the properties value of each element of mm1 and mm2 are equal.
I'm trying to convert the validate method in functional programming style. But don't know how to deal with the checking of all of mm1 item should be in mm2.
Here what I tried with for-comprehension:
def validate2(mm1: List[Map[String, Any]], mm2: List[M]): Boolean = { for { m1 <- mm1 a = m1("a") m2 <- mm2 } { if (a == m2.a) { assert(m1("b") == m2.b) } } true } Not really good, since I can't put var found = false inside the for comprehension. So I can't do a checking if all items in mm1 exist in mm2.
Anyone can help or have better idea (maybe using recursion or without using var found at all) ?