具有函数作为参数的Case类

时间:2017-05-28 16:12:12

标签: scala generics

我已经定义了3个案例类如下:

case class Func1(inputA: HashMap[String, String], mapFn: (String, String) => List[(String, Int)], redFn: (String, List[Int]) => (String, Int))
case class Func2(inputB: HashMap[String, String], mapFn: (String, String) => List[(String, String)], redFn: (String, List[String]) => (String, List[String])) 
case class Func3(inputC: HashMap[String, String], mapFn: (String, String) => List[(String, String)], redFn: (String, List[String]) => (String, Int)) 

在接收方法中,我有与上述相符的相应案例:

case Func1(inputA, mapFn, redFn) =>  // Do something
case Func2(inputB, mapFn, redFn) =>  // Do something
case Func3(inputC, mapFn, redFn) =>  // Do something

是否可以用一个通用案例类替换3个案例类?

我尝试了以下内容:

我按如下方式定义了案例类:

case class Func[K, V, X, Y, U](input: HashMap[K, V], mapFn: (K, V) => List[(X, Y)], redFun: (X, List[Y]) => (X, U))

然后,在MyActor类的receive方法中,我有:

case Func[K, V, X, Y, U](input: HashMap[K, V], mapFn: (K, V) => List[(X, Y)], redFun: (X, List[Y]) => (X, U))  =>  //code here

编译错误如下。第一个错误表示错误位于=>

中的mapFn: (K,V) => List[(X,Y)]
  ')' expected but '=>' found.

  [error]   case MapIt[K, V, X, Y, U](input: HashMap[K, V], mapFn: (K,V) => List[(X, Y)], redFun: (X, List[Y]) => (X, U))  =>

第二个错误表示问题出现在" mapFn:(K,V)=>的最后一个方括号内(逗号之前)列出[(X,Y)],"

  '=>' expected but ']' found.

  [error]   case Func[K, V, X, Y, U](input: HashMap[K, V], mapFn: (K, V) => List[(X, Y)], redFun: (X, List[Y]) => (X, U))  =>

1 个答案:

答案 0 :(得分:1)

如果有帮助,请告诉我。

 case class FuncG[K, V, X, Y, U](input: HashMap[K, V], mapFn: (K, V) => List[(X, Y)], redFun: (X, List[Y]) => (X, U))   
  val firstParam: HashMap[String, String] = HashMap("test key" -> "test value")

  def mapfn1(a1:String, a2:String):List[(String, Int)] = List(("val1",4))
  def mapfn2(a1:String, a2:String):List[(String, String)] = List(("val2","val3"))

  def redfn1(r1:String, r2:List[Int]):(String, Int) = ("val4",56)
  def redfn2(r1:String, r2:List[String]):(String, List[String]) = ("val4",List("val5"))
  def redfn3(r1:String, r2:List[String]):(String, Int) = ("val6",34)

  val pattern1 = FuncG(firstParam,mapfn1,redfn1)
  val pattern2 = FuncG(firstParam,mapfn2,redfn2)
  val pattern3 = FuncG(firstParam,mapfn2,redfn3)

  def doMatch(pattern:Any) = {
    pattern match {
      case FuncG(inputA, mapFn, redFun)  =>  println("Found")
    }
  }

  doMatch(pattern1)
  doMatch(pattern2)
  doMatch(pattern3)