I am coming from Java background and learning Scala now. I have a Seq
respectively for Loc
and LocSize
objects whereby these 2 objects share a common member field code
. I have a validateRoom
function that basically validates these two Seq
by matching a Loc
instance to a LocSize
instance and make some basic validation operations. My objective is to make sure all Loc objects passes the validation, hence I am using Seq.forall
at the last println
.
I believe that there are better, shorter and prettier FP ways to achieve what I want. How can I do so?
case class Loc(id: String, code: String, isRoom: Boolean, measureUnit: String, allowedSize: Int)
case class LocSize(code: String, width: Int, length: Int, measureUnit: String)
val locs = Seq(
Loc("_1", "loc01", true, "M", 100),
Loc("_2", "loc02", false, "M", 100),
Loc("_3", "loc03", true, "M", 100)
)
val locSizes = Seq(
LocSize("loc01", 5, 10, "M"),
LocSize("loc02", 6, 11, "M"),
LocSize("loc03", 9, 14, "M"),
LocSize("loc04", 8, 13, "M"),
LocSize("loc05", 9, 14, "M"),
)
def validateRoom(locs: Seq[Loc], loSizes: Seq[LocSize]): Seq[Boolean] = {
for (loc <- locs) yield {
if (loc.isRoom) {
val locSize = loSizes.find(_.code == loc.code)
locSize match {
case Some(i) => {
if (i.measureUnit.contains(loc.measureUnit) &&
i.width*i.length < loc.allowedSize)
true
else
false
}
case None => false
}
}
else
true
}
}
// Return false as loc03 size 9*14 > 100
println(validateRoom(locs, locSizes).forall(b => b))