我想增强基于混合技术的模式匹配,例如:
trait Base {
def match(x:Any):String
}
trait HandleAString {
def match(x:Any):String = x match {
case "A" => "matched A string"
}
}
trait HandleOneInt {
def match(x:Any):String = x match {
case x:Int if (x==1) => "matched 1 int"
}
}
//main
val handler = new Base extends HandleOneInt with HandleAString
println(handler.match("a") ) //should print "matched A string"
println(handler.match(1) ) //should print "matched 1 int"
println(handler.match(2) ) //should throw exception
如果您有任何其他技术,我想听听...
老实说,混入方面有点过度抽象-我敦促您仔细考虑您实际想要实现的目标,并寻找一种更简单的方法。我在mixin方面无济于事,但是您可以将单个匹配用例存储为a,PartialFunction
然后将多个using组合使用orElse
,这可能会满足您的要求,或者至少会为您指明前进的方向:
val handler1: PartialFunction[Any, String] = {
case "A" => "matched A string"
}
val handler2: PartialFunction[Any, String] = {
case x:Int if (x==1) => "matched 1 int"
}
val manyHandlers = List(handler1, handler2)
val handler = manyHandlers.reduce(_.orElse(_))
println(handler("A") ) // "a" won't match, match is exact
println(handler(1) )
println(handler(2) )
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句