如何匹配列表元素

How to match on list element

我想匹配列表中是否包含某个元素,return根据元素的不同得到不同的结果。我用if else的方式写的,现在想用match case来写,但是我对match case不是很熟悉,谁能帮我写case matching的方式,谢谢

下面是 if else

的代码
   val sten=List(sort_view.head._1,sort_view(1)._1)
  if(sten.contains("Positive")) println("Positive")
  else if (sten.contains("Neutral")) println("Neutral")
  else if (sten.contains("Negative")) println("Negative")
  else if (sten.contains("Verynegative")) println("Verynegative")

您可以过滤并获得第一个结果:

List("Positive", "Neutral", "Negative", "Verynegative")
    .filter(sten.contains)
    .headOption
    .foreach(println)

在这种情况下,它比模式匹配更简单、更清晰。