代码之家  ›  专栏  ›  技术社区  ›  Dariusz Krynicki

字符串序列中值的scala模式匹配

  •  0
  • Dariusz Krynicki  · 技术社区  · 4 年前

    变量someKey可以是“a”、“b”或“c”。

    我可以这样做:

    someKey match {
        case "a" => someObjectA.execute()
        case "b" => someOther.execute()
        case "c" => someOther.execute()
        case _ => throw new IllegalArgumentException("Unknown")
    }
    

    如何压缩此模式匹配,以便检查某个键是否与Seq(“b”、“c”)匹配,如果它在序列中,则将两行模式匹配替换为一行?

    编辑:

    someKey match {
            case "a" => someObjectA.execute()
            case someKey if Seq("b","c").contains(someKey) => someOther.execute()
            case _ => throw new IllegalArgumentException("Unknown")
        }
    
    0 回复  |  直到 4 年前
        1
  •  2
  •   Dima    4 年前

    你可以把“或”放在 case 条款:

    someKey match {
        case "a" => someObjectA.execute()
        case "b"|"c" => someOther.execute()
        case _ => ???
    }
    
        2
  •  1
  •   Levi Ramsey    4 年前

    对于这种特殊情况,我可能会去

    // 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")
    }