0

I have an Object

object Constants {
  val getA = "example.a.test"
  val getB = "example.b.test"
  val getC = "example.c.test"
        .
        .
        .
}

I have another class where I'm accessing these values after importing the class in an if-else loop

if(str == "A") {
   println(Constants.getA)
}
else if (str == "B") {
   println(Constants.getB)
} else {
   println(Constants.getC)
}
// and so on...

NOTE: This is just a sample code I have but the if-else loops get complicated. Is there a way to simplify this by passing the "str" variable directly to the object like "Constants.get$str" or something simpler? I get Cyclomatic complexity Scala check style warning

1
  • 1
    I'm guessing there's some reason why Constants can't be a Map[K,V], i.e. Map("A" -> "example.a.test")? Commented Jan 22, 2020 at 5:25

2 Answers 2

2

You can use pattern matching and create a new function in Constant.

def getString(str: String) = {
 str match {
  case "A" => "example.a.test"
  case "B" => "example.b.test"
  case "C" => "example.c.test"
  case _ => "Wrong input"
 }
}
Sign up to request clarification or add additional context in comments.

Comments

2

you can use a key/value object for handle your code

for example use Map :

object Constants {
val get = Map("A" -> "example.a.test", "B" -> "example.b.test", "C" -> "example.c.test" , ...)
}

and you can use it by

println( get("A"))

instead of all if else loop which you had . you can even iterate on the keys or values too :

  get.keys.foreach{ i =>  
     print( "Key = " + i )
     println(" Value = " + get(i) )}

i think this way could be simpler and i hope the answer is useful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.