Scala: Pattern matching when one of two items meets some condition

前端 未结 6 1776
野趣味
野趣味 2021-02-20 12:53

I\'m often writing code that compares two objects and produces a value based on whether they are the same, or different, based on how they are different.

So I might writ

6条回答
  •  感情败类
    2021-02-20 13:19

    On Scala 2.8:

    val result = List(v1,v2).flatten match {
      case List(value1, value2) => "a"
      case List(value) => "b"
      case _ = > "c"
    }
    

    On Scala 2.7, however, you need a type hint to make it work. So, assuming value is Int, for instance, then:

    val result = (List(v1,v2).flatten : List[Int]) match {
      case List(value1, value2) => "a"
      case List(value) => "b"
      case _ = > "c"
    }
    

    The funny thing about it is that I misread "first" as "list" on Mitch Blevins answer, and that gave me this idea. :-)

提交回复
热议问题