Scala: short form of pattern matching that returns Boolean

后端 未结 6 2115
灰色年华
灰色年华 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 03:57

    The best I can come up with is this:

    def matches[A](a:A)(f:PartialFunction[A, Unit]) = f.isDefinedAt(a)
    
    if (matches(a){case ... =>}) {
        //do stuff
    }
    

    This won't win you any style points though.

提交回复
热议问题