我编写了类似于下面给出的代码。它按照(有点令人困惑的)要求工作,但有些东西告诉我它可以在 Scala 中使用“模式匹配”或类似的东西以不同的方式编写,以使其看起来更实用。有什么建议么?
def xyzMethod(map: util.HashMap[Any, List[SomeObject]]) : Option[xyzObject] = {
var myObject: Option[xyzObject] = None
val cCount: Int = map.get("c").size
if (cCount != 10) {
val bCount: Int = map.get("b").size
if (bCount + cCount == 20) {
myObject = buildXyz("b")
} else {
val aCount: Int = map.get("a").size
if (aCount != 0) {
val dCount: Int = map.get("d").size
if (dCount > 10) {
myObject = buildXyz("a")
}
}
}
}
myObject
}
根据要求,这里有一些测试用例:
Test Case 1:
map =>
"c" => Objectc1, Objectc2... Objectc10
This should return None
-----------
Test Case 2:
map =>
"c" => Objectc1, Objectc2
"b" => Objectb1, Objectb2..... Objectb18
This should return buildXyz("b")
-----------
Test Case 3:
map =>
"c" => Objectc1
"b" => Objectb1, Objectb2
This should return None
-----------
Test Case 4:
map =>
"c" => Objectc1
"b" => Objectb1, Objectb2
"a" => Objecta1
"d" => Objectd1
This should return None
-----------
Test Case 5:
map =>
"c" => Objectc1
"b" => Objectb1, Objectb2
"a" => Objecta1
"d" => Objectd1, Objectd2......Objectd10, Objectd11
This should return buildXyz("a")