NoName
NoName

Reputation: 1749

Scala: How to pass string variables to access Object values?

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

Upvotes: 0

Views: 707

Answers (2)

Hadi Rahjoo
Hadi Rahjoo

Reputation: 185

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.

Upvotes: 2

Mahesh Chand
Mahesh Chand

Reputation: 3250

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

Upvotes: 2

Related Questions