Scala: short form of pattern matching that returns Boolean

后端 未结 6 2106
灰色年华
灰色年华 2020-12-01 03:28

I found myself writing something like this quite often:

a match {     
  case `b` => // do stuff
  case _ => // do nothing
}

Is there

6条回答
  •  遥遥无期
    2020-12-01 04:12

    Kim's answer can be “improved” to better match your requirement:

    class AnyWrapper[A](wrapped: A) {
      def matches(f: PartialFunction[A, Unit]) = f.isDefinedAt(wrapped)
    }
    implicit def any2wrapper[A](wrapped: A) = new AnyWrapper(wrapped)
    

    then:

    val a = "a" :: Nil
    if (a matches { case "a" :: Nil => }) {
      println("match")
    }
    

    I wouldn't do it, however. The => }) { sequence is really ugly here, and the whole code looks much less clear than a normal match. Plus, you get the compile-time overhead of looking up the implicit conversion, and the run-time overhead of wrapping the match in a PartialFunction (not counting the conflicts you could get with other, already defined matches methods, like the one in String).

    To look a little bit better (and be less verbose), you could add this def to AnyWrapper:

    def ifMatch(f: PartialFunction[A, Unit]): Unit = if (f.isDefinedAt(wrapped)) f(wrapped)
    

    and use it like this:

    a ifMatch { case "a" :: Nil => println("match") }
    

    which saves you your case _ => line, but requires double braces if you want a block instead of a single statement... Not so nice.

    Note that this construct is not really in the spirit of functional programming, as it can only be used to execute something that has side effects. We can't easily use it to return a value (therefore the Unit return value), as the function is partial — we'd need a default value, or we could return an Option instance. But here again, we would probably unwrap it with a match, so we'd gain nothing.

    Frankly, you're better off getting used to seeing and using those match frequently, and moving away from this kind of imperative-style constructs (following Madoc's nice explanation).

提交回复
热议问题