用于验证过滤器仅返回一个结果(或该项中的特定金额)的最佳Scala惯用方法是什么?如果数量正确,则继续使用它?
例如:
String line = "\"USE CODE \"\"Gef, sdf\"\" FROM 1/7/07\", Delete , Hello , How are you ? , ";
String line2 = "Test asda ds asd, tesat2 . test3";
Pattern pattern = Pattern.compile("(?:\"[^\"]*(?:\"\"[^\"]*)*\"|[^,])+");
Matcher matcher = pattern.matcher(line);
if (matcher.find()){ // if is used to get the 1st match only
System.out.println(matcher.group(0));
}
Matcher matcher2 = pattern.matcher(line2);
if (matcher2.find()){
System.out.println(matcher2.group(0));
}
答案 0 :(得分:1)
考虑这个类型T
,
val myFilteredListWithDesiredOneItem = {
val xs = unfilteredList.filter(x => x.getId.equals(something))
if (xs.size == n) xs.toList
else List.empty[T]
}
不是oneliner,代码仍然很简单。
答案 1 :(得分:0)
尝试与守卫比赛,也许?
list.filter(...) match {
case Nil => // empty
case a if (a.size == 5) => // five items
case b@(List(item1, item2) => // two (explicit) items
case _ => // default
}
答案 2 :(得分:-3)
或许这样的事情:
Option(list.filter(filterFunc))
.filter(_.size == n)
.getOrElse(throw new Exception("wrong size!"))