首页 > 解决方案 > 如何匹配列表元素

问题描述

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

下面是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")

标签: scalafunctional-programmingpattern-matchingcasescala-collections

解决方案


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

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

在这种情况下,它比模式匹配更容易和更干净。


推荐阅读