Scala模式与mixin匹配

时间:2014-11-12 14:47:36

标签: scala

我想基于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  

如果您有任何其他技术我想听听......

1 个答案:

答案 0 :(得分:5)

老实说,混合方面有过度抽象的气味 - 我敦促你仔细思考你实际想要实现的目标,并寻找一种更简单的方法。我无法帮助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) )