scala - 重构字符串列表的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
不起作用
解决方案
大多数其他答案似乎都涉及修复选项的使用,或远离模式匹配(简单地使用警卫并不是真正的模式匹配,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
推荐阅读
- javascript - 正则表达式替换“
" 括号 - web - 我对苹果主页很好奇
- hadoop - 如何在没有 hadoop 的情况下安装 pyspark?
- c# - What would be the best option to display class properties in a Microsoft.Toolkit.Uwp.UI.Controls.DataGrid?
- android - 在 Google Play 商店发布后,新创建的应用程序无法运行
- javascript - JavaScript 以一种聪明的方式创建带有子数组的对象/数组/在 JavaScript 中复制 PHP 数据结构
- python - left 删除字符串中第二个数字之前的任何内容
- r - 在折线图的特定位置添加点或点,并使用 ggplotly() 相应地调整工具提示
- docker - Docker 容器中的 Headless Cypress 分辨率始终为 1280x1024
- linux - 在 bash 脚本中添加请求的参数作为变量