我可以在scala中组合多个字符串匹配案例吗?

时间:2017-06-05 22:18:21

标签: scala

我可以将以下两种情况合并为一个@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tab_calculadora, container, false); screen = (TextView) view.findViewById(R.id.txtScreen); screen.setText(""); Button yourButton = (Button)view.findViewById(R.id.yourButtonId); yourButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickNumber(v); } }); return view; } 子句,因为它们都做同样的事情吗?

case

另外,如果我想使用e match { case "hello" => e + "world" case "hi" => e + "world } 进行匹配,例如

startsWith

1 个答案:

答案 0 :(得分:3)

是的,您只需使用or (|) match pattern之一{/ 1}},

scala> "hi" match { case "hello" | "hi" => println("fantastic")  case _ => println("very very bad")}
fantastic

scala> "hello" match { case "hello" | "hi" => println("fantastic")  case _ => println("very very bad")}
fantastic

scala> "something else" match { case "hello" | "hi" => println("fantastic")  case _ => println("very very bad")}
very very bad

您还可以使用正则表达式进行模式匹配,尤其适用于需要匹配的标准时,

scala> val startsWithHiOrHello = """hello.*|hi.*""".r
startsWithHiOrHello: scala.util.matching.Regex = hello.*|hi.*

scala> "hi there" match { case startsWithHiOrHello() => println("fantastic")  case _ => println("very very bad")}
fantastic

scala> "hello there" match { case startsWithHiOrHello() => println("fantastic")  case _ => println("very very bad")}
fantastic

scala> "non of hi or hello there" match { case startsWithHiOrHello() => println("fantastic")  case _ => println("very very bad")}
very very bad

请参阅Scala multiple type pattern matchingScala match case on regex directly