字符串序列中值的scala模式匹配
变量someKey可以是a、b或c 我可以这样做:字符串序列中值的scala模式匹配,scala,design-patterns,sequence,matching,Scala,Design Patterns,Sequence,Matching,变量someKey可以是a、b或c 我可以这样做: someKey match { case "a" => someObjectA.execute() case "b" => someOther.execute() case "c" => someOther.execute() case _ => throw new IllegalArgumentException("U
someKey match {
case "a" => someObjectA.execute()
case "b" => someOther.execute()
case "c" => someOther.execute()
case _ => throw new IllegalArgumentException("Unknown")
}
如何压缩此模式匹配,以便检查某个键是否与Seqb、c匹配,以及是否在序列中,然后将两行模式匹配替换为一行
编辑:
对于这种特殊情况,我可能会去
// likely in some companion object so these get constructed once
val otherExecute = { () => someOther.execute() }
val keyedTasks = Map(
"a" -> { () => someObjectA.execute() },
"b" -> otherExecute,
"c" -> otherExecute
)
// no idea on the result type of the execute calls? Unit?
def someFunction(someKey: String) = {
val resultOpt = keyedTasks.get(someKey).map(_())
if (resultOpt.isDefined) resultOpt.get
else throw new IllegalArgumentException("Unknown")
}
在case子句中,您可以有或:
如果seq.containsk也可以使用case k,我会使用Set而不是seq。你也可以有一个从key到computation或者到一个具有execute的公共类型的映射。这更像是一个switch case语句,而不是模式匹配,但无论如何,我不完全理解你的意思,但是如果你想使用相同的功能匹配Seq中的元素,你可以将这段代码转换成一个函数,然后将函数作为映射参数传递到seq中。mapfunction@LuisMiguel Mejía Suárez是的,赛特完成了任务。TY@AminMal请看我的编辑。若你们想做一些有价值的事情,我不想使用GetOrelsThrow或者折叠。我在这里是为了说教的清晰性。。。考虑到我的druthers,我会在类型系统中对此进行建模。
// likely in some companion object so these get constructed once
val otherExecute = { () => someOther.execute() }
val keyedTasks = Map(
"a" -> { () => someObjectA.execute() },
"b" -> otherExecute,
"c" -> otherExecute
)
// no idea on the result type of the execute calls? Unit?
def someFunction(someKey: String) = {
val resultOpt = keyedTasks.get(someKey).map(_())
if (resultOpt.isDefined) resultOpt.get
else throw new IllegalArgumentException("Unknown")
}
someKey match {
case "a" => someObjectA.execute()
case "b"|"c" => someOther.execute()
case _ => ???
}