在字符串的枚举中搜索

时间:2017-05-17 01:09:24

标签: scala

我们如何在字符串枚举中搜索字符串?

object FilterByDimensions extends Enumeration {
  type FilterByDimensions = String
  val Instance = "Instance"
  val Platform = "Platform"
  val Region = "Region"

  def isSupported(s: String) = 
  FilterByDimensions.values.exists(_.toString.equalsIgnoreCase(s))
}

此方法无效。试过这个。

def isSupported(s: String) = 
  FilterByDimensions.values.exists(_.equalsIgnoreCase(s))

2 个答案:

答案 0 :(得分:1)

如果我了解您要检查FilterByDimension enum中是否存在字符串的问题,那么您的FilterByDimension应如下所示

object FilterByDimensions extends Enumeration {
  type FilterByDimensions = String
  val Instance = Value("Instance")
  val Platform = Value("Platform")
  val Region = Value("Region")

  import scala.util.control.Breaks._
  def isSupported(s: String) = {
    var exists = false
    breakable {
      for(value <- FilterByDimensions.values){
      exists = s.equalsIgnoreCase(FilterByDimensions(value.id).toString)
      if(exists){
        break
      }
    }
    }
    exists
  }
}

<强>被修改
对于模式匹配,最好使用case class

case class FilterByDimensions(value: String)

object FilterByDimensions {
  object Instance extends FilterByDimensions("Instance")
  object Platform extends FilterByDimensions("Platform")
  object Region extends FilterByDimensions("Region")

  val values = Seq(Instance, Platform, Region)
}

您可以按以下方式调用

val ins = "Instance"
    ins match {
      case FilterByDimensions.Instance.value => println("instance match")
      case FilterByDimensions.Instance.value => println("progressing")
      case FilterByDimensions.Instance.value => println("region match")
      case _ => println("doesn't match")
    }

答案 1 :(得分:1)

也许你正在寻找:

scala> object X extends Enumeration { val Y = Value }
defined object X

scala> def f(s: String) = util.Try(X.withName(s)) match { case util.Success(X.Y) => "ok" case _ => "nope" }
f: (s: String)String

scala> f("Y")
res0: String = ok

scala> f("Z")
res1: String = nope

人们要求的两个小功能是按名称匹配,并按姓名查找,不会抛出。