2

I wanted to know is there any way to write method's body dynamically. i.e. Reading conditions from XML or JSON and depending on these conditions defining method's body.

If I have not expressed the example in right way please forgive me.

Ex:

def read(conds: Array[String])={
    var str = ""
    for(i <- 0 to conds.length - 1){
      if(conds(i) == "1"){
        //add if code to str
        //if(){
          //if cond code here
        //}
      }else if(conds(i) == "2"){
        //add else if code to str
        //else if(){
          //else if cond code here
        //}
      }else if(conds(i) == "3"){
        //add else code to str
        //else{
          //else code here
        //}
      }
    }

    //at the end str has multiple conditions
    //Ex:
    //str = "if(){....}"+
    //"esle if(){....}"+
    //"esle if(){....}"+
    //"esle if(){....}"+
    //"esle{....}"
    //so all the code present in string should be body of method
  }
Sam
  • 139
  • 1
  • 10
  • No. Why can't you just write a normal if statement instead? – Salem Jul 19 '17 at 10:52
  • Because I have to build these conditions on the basis of xml or json input. Some time there may be few conditions, and some time there may of n number of conditions. – Sam Jul 19 '17 at 10:58
  • I am not sure what you mean but can you not just keep a boolean variable and continuously `and` it with the conditions you get? Other than that no an `eval` like function does not exist. – Salem Jul 19 '17 at 10:59
  • what about abstract read method/function? – matoni Jul 19 '17 at 11:20
  • @Sam, so basically you can build the `str` as you need and your question is about a way to generate a compiled code from the `str` and run it, right? If this is your intent then you need to go here https://stackoverflow.com/questions/12122939/generating-a-class-from-string-and-instantiating-it-in-scala-2-10 – Alexander Arendar Jul 19 '17 at 11:43

1 Answers1

0

We are using Scala macros to automatically generate our api from a json file.

hich9n
  • 1,578
  • 2
  • 15
  • 32