调用方法动态地基于Scala中的param

时间:2016-10-23 05:37:29

标签: scala

我在scala的课堂上咆哮

 class A(arg:String){

 // this method is going to call many time 
 def exce():String ={
 // i do not want to use if else here
 if("arg"=="a1")
 a1("abc")
 if("arg"=="a1")
  a2("abc")
 }
 def a1(arg1:String):String={
 "in a1"
 }
 def a2(arg1:String):String={
 "in a2"
 }
 }

我将创建A类的实例,现在将arg值作为方法名称传递     我如何调用方法" exce",而exce方法将根据args调用a1或a2     喜欢     new A(" a1")。exce() - 输出为a1     如何在不使用if的情况下实现这一目标" exce"方法

可以帮助一些人

2 个答案:

答案 0 :(得分:1)

如果我理解正确的话。我认为这可以解决你的用例:

class A(arg:String){
  def exce():String = arg match{
    case "a1"=>a1("abc")
    case "a2"=>a2("abc")
  }

  def a1(arg1:String):String={
    "in a1"
  }
  def a2(arg1:String):String={
    "in a2"
  }
}

现在致电new A("a1").exec() 然后它给出了in a1

答案 1 :(得分:1)

首先,您的方法a1,a2,exec是公开的,但为什么您希望间接调用方式exec()->a1() or a2()? 。我假设您错过了将私有内容添加到a1a2。如果要多次调用exec方法,则应将方法名称作为exec(name:String)传递。如果要调用新方法,则必须创建新的A实例。模式匹配将是if-else

的替代方案
class A{

  private def a1(arg1: String): String = {
    "in a1"
  }
  private def a2(arg1: String): String = {
    "in a2"
  }

  def exec(funName: String): String = {

    funName match {
 //You can think about passing input param "abc" from caller as well.
      case "a1" => a1("abc")
      case "a2" => a2("abc")
    }

  }

}

object Main extends App {

val a =new A()
println(a.exec("a1"))
println(a.exec("a2"))

}

结果:

  

in a1

     

in a2

或者,如果您不希望将其作为方法参数传递,则可以将 args as val

    class  A(val args:String){

    // your a1,a2 methods goes here

 def exec(): String = {

    args match {
 //You can think about passing input param "abc" from caller as well.
      case "a1" => a1("abc")
      case "a2" => a2("abc")
    }
    }

    object Main extends App {

    val a =new A("a1")
    println(a.exec())
    a.args = "a2"
    println(a.exec())

    }

结果:

  

in a1

     

in a2