首页 > 解决方案 > 重构字符串列表的scala匹配案例

问题描述

我有以下内容:

def myFunc(str: String): Something => {

    str match {
        case "a" | "a1" | "abc" | "qwe" | "23rs" => Something
        case _ => None
    }    
}

字符串列表可能很长,我想将其提取到一个函数中。我真的不知道要搜索什么,因为做

def isSomething(str: String): Boolean => {
  List("a","a1","abc","qwe","23rs").contains(str)
}

case isSomething => Something不起作用

标签: scalapattern-matchingmatch

解决方案


大多数其他答案似乎都涉及修复选项的使用,或远离模式匹配(简单地使用警卫并不是真正的模式匹配,IMO)

我想你可能会问关于提取器的问题。如果是这样,这可能更接近您想要的:

  case class Something(str: String)

  // define an extractor to match our list of Strings

  object MatchList {
    def unapply(str: String) = {
      str match {
        case "a" | "a1" | "abc" | "qwe" | "23rs" => Some(str)
        case _                                   => None
      }
    }
    }

    def myFunc(str: String): Option[Something] = {

      // use our new extractor (and fix up the use of Option while we're at it)    
      str match {
        case MatchList(str) => Some(Something(str))
        case _              => None
      }
    }

// Couple of test cases...
    myFunc("a")    // Some(Something(a))
    myFunc("b")    // None

推荐阅读