带参数的动态对象创建

Dynamic object creation with arguments

场景: 这是以下博客中提到的要求的修改版本。

我有一个 senario,我需要一个一个地调用 class,它根据用户的输入提供者实现特征,如果没有提供它应该调用所有处理器 class 和过程( ) 里面的方法。

trait Processor {
  def process(str:String)=println("default process")
}
case class ProcessorOne() extends Processor
case class ProcessorTwo() extends Processor {
  override def process(str:String)=println("process:"+str)
}
case class ProcessorThree() extends Processor {
  override def process(str:String)=println("process:"+str)
}

现在我的问题是如何创建一个 Map[String,Class] 以根据用户输入的键动态选择特定的 class 并传递用户正在传递的特定参数。

val myFuncs =
  Map("string1" -> (() => ProcessorOne().process),
    "string2" -> (() => ProcessorTwo().process),
  "string3" -> (() => ProcessorThree().process))

假设用户将 string2 说成键并将其对应的 class 参数说成 15。 我应该得到输出 process:15.

如果用户将 string3 作为键传递,class 参数作为 20 传递。那么应该调用处理器 3 的相应对象并输出 process:20。应该打印出来。

我是 Scala 新手。请为我指教。欢迎任何其他使用用户提供的参数动态选择 scala classes 的方法。

您实际上不需要 'dynamically picking' class。 你想要一个函数,它创建一个新对象的选择 class。 您的变体

val myFuncs =
  Map("string1" -> (() => ProcessorOne().process),
      "string2" -> (() => ProcessorTwo().process),
      "string3" -> (() => ProcessorThree().process))

还不错

所以假设我们有用户输入作为函数的参数

object SomeServiceThatProcessUserInput {
  private val implementationCreators: Map[String, () => Processor] = 
    Map(
      "string1" -> () => ProcessorOne(),
      "string2" -> () => ProcessorTwo(),
      "string3" -> () => ProcessorThree()
    )

  def processUserInput(implementationChooseString: String, anotherInput: String) = {
    val implementationCreator: () => Processor = implementationCreators .get(implementationChooseString).getOrElse(throw new Exceprtion())
    val implementation: Processor = implementationCreator()
    implementation.process(anotherInput)
  }
}

你根本不需要处理 Class

如果您想使用包含额外 .process 的地图:

object SomeServiceThatProcessUserInput {
  private val implementationFunctionCreators: Map[String, () => String => Unit] = 
    Map(
      "string1" -> () => ProcessorOne().process,
      "string2" -> () => ProcessorTwo().process,
      "string3" -> () => ProcessorThree().process
    )
  def processUserInput(implementationChooseString: String, anotherInput: String) = {
    val implementationFunctionCreator: () => String => Unit = implementationFunctionCreators.get(implementationChooseString).getOrElse(throw new Exceprtion())
    val implementationFunction: String => Unit= implementationFunctionCreator()
    implementationFunction(anotherInput)
  }
}