簡體   English   中英

Scala模式與Mixins匹配

[英]Scala pattern matching with mixins

我想增強基於混合技術的模式匹配,例如:

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方面PartialFunction ,但是您可以將一個匹配用例存儲為PartialFunction並使用orElse組合多個匹配用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) )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM