How to use scala class member name as variable

Viewed 3421

In scala, is there a way to access a class member,but the member name is a var? Below is a code snippet, there is a class member called "one_star". I have a var whose value is "one_star", and I want use this var as the member name of the "case class".

case class Features(
  // star about
  var one_star: String = "0",
  var two_star: String = "0",
  var three_star: String = "0",
  var four_star: String = "0",
  var five_star: String = "0"

  // other about
)

object Features {
  def apply(): Features = {
    val features = new Features()
    var testVar = "one_star"
    features.${testVar} = "1"
    features
  }
}
3 Answers
Related