本文介绍了如何在地图中调用此对象方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Problem : I have to call Objects methods which stored in a map, for a given key how to do it ?Code :

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 ???
  }
}

推荐答案

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

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

but Processor20().process is a function that you could save in map

尝试类似的东西:

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)
}

这篇关于如何在地图中调用此对象方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 19:57