Scala: short form of pattern matching that returns Boolean

后端 未结 6 2114
灰色年华
灰色年华 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:22

    Patterns can also be used in for expressions. Your code sample

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

    can then be expressed as

    for(b <- Some(a)) //do stuff
    

    The trick is to wrap a to make it a valid enumerator. E.g. List(a) would also work, but I think Some(a) is closest to your intended meaning.

提交回复
热议问题