我有以下用例,我知道模式匹配在Scala中是如何工作的,但是我有一个需要根据模式分配值的条件,我想避免重复代码,是否有最好的方法可以实现?请让我知道
测试值的样本值将是带有定界符','的字符串
cf match {
case "1" =>
val info1 => test.split(",")
val info2 => test2.split(",")
val info3 => test3.split(",")
val info4 => test4.split(",")
val info5 => test5.split(",")
case "2" =>
val info1 => test6.split(",")
val info2 => test7.split(",")
val info3 => test8.split(",")
val info4 => test9.split(",")
val info5 => test10.split(",")
}
预先感谢
答案 0 :(得分:4)
最好的方法是
val cf = "1"
val test1 = "a,b,c"
val test2 = "d,e,f"
val test3 = "g,h,i"
val test4 = "j,k,l"
val (info1, info2, info3, info4, info5) = cf match {
case "1" => (test1.split(","), test2.split(","), test1.split(","), test2.split(","), test1.split(","))
case "2" => (test3.split(","), test4.split(","), test3.split(","), test4.split(","), test3.split(","))
}
info1.toList.foreach{println}
info2.toList.foreach{println}
info3.toList.foreach{println}
info4.toList.foreach{println}
info5.toList.foreach{println}
这样,您可以分别引用每个值。
模式匹配中的任何val声明都将在本地范围内,因此从技术上讲,您案例中的所有val声明都将“返回”单位(如果是=而不是=>)
编辑:响应您的编辑。这适用于任何类型。您可以定义一个映射元组的函数,这样就不必单独拆分
这是一个工作的小提琴:https://scastie.scala-lang.org/Hcpmn0OsTr6RLWkUyUFVVQ 您可以看到它打印正常