我想基于mixin技术增强模式匹配,例如:
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
Run Code Online (Sandbox Code Playgroud)
如果你有任何其他技术我想听到...
老实说,混合方面有过度抽象的气味 - 我敦促你仔细思考你实际想要实现的目标,并寻找一种更简单的方法.我无法帮助mixin方面,但你可以将一个匹配案例存储为一个PartialFunction并使用几个组合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) )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
256 次 |
| 最近记录: |