如何在地图中调用此对象方法?

时间:2018-10-26 08:37:15

标签: scala apache-spark

问题:我必须调用存储在地图中的Objects方法,对于给定的键该怎么做? 代码:

trait Processor00 {
  def process(x:String): Unit
}
case class Processor20() extends Processor0 {
   override def process(x:String): Unit = println("Processor20 x :" + x)
}
case class Processor30() extends Processor0 {
   override def process(x:String): Unit = println("Processor30 x :" + x)
}
object UnitTest1 {
  def main( args : Array[String]):Unit ={
    val s:String = "yes"
    val myFuncs: Map[String,(String) => Unit ]=  Map(  
           "string2" -> Processor20().process(s), //Eroor 1. type mismatch; found : Unit required: String ⇒ Unit
          "string3" -> Processor30().process(s)
        )
   myFuncs.values.foreach(v => v());//how to call all  Objects' i.e.  process("Hi") here ???
  }
}

1 个答案:

答案 0 :(得分:1)

Processor20().process(s)被称为函数process,并返回Unit

但是Processor20().process是可以保存在地图中的功能

尝试类似的东西:

trait Processor00 {
  def process(x:String): Unit
}
case class Processor20() extends Processor00 {
  override def process(x:String): Unit = println("Processor20 x :" + x)
}
case class Processor30() extends Processor00 {
  override def process(x:String): Unit = println("Processor30 x :" + x)
}


object Main extends App {
  val s: String = "yes"
  val myFuncs: Map[String, String => Unit] = Map(
    "string2" -> Processor20().process,
    "string3" -> Processor30().process
  )
  myFuncs.foreach { case (key, f) => f(s) } // or f(key)
}