Scala具有支持模式匹配中的析取的语言功能('Pattern Alternatives'):
x match {
case _: String | _: Int =>
case _ =>
}
Run Code Online (Sandbox Code Playgroud)
但是,如果仔细检查满足PatternA 和 PatternB(连接),我经常需要触发一个动作.
我创建了一个模式组合器'&&',它增加了这个功能.三条小线条让我想起为什么我爱斯卡拉!
// Splitter to apply two pattern matches on the same scrutiny.
object && {
def unapply[A](a: A) = Some((a, a))
}
// Extractor object matching first character.
object StartsWith {
def unapply(s: String) = s.headOption
}
// Extractor object matching last character.
object EndsWith {
def unapply(s: String) = s.reverse.headOption
}
// Extractor object matching length.
object Length {
def …Run Code Online (Sandbox Code Playgroud)