How to remove datatype from value in config file w

2019-08-06 03:49发布

问题:

I have a config file beam-template.conf which has different properties like

   `beam.agentsim.agents.rideHail.keepMaxTopNScores = "int | 1"
    beam.agentsim.agents.rideHail.minScoreThresholdForRepositioning = "double | 0.1"`

I am trying to get the properties values like this.

  Configfactory.parseFile(new File(path/beam-template.conf)).entrySet().asScala.foreach { entry =>
    if (!(userConf.hasPathOrNull(entry.getKey))) {
      logString+="\nKey= " + entry.getKey + " ,Value= " + entry.getValue.render
    }
}

So the problem is this that the values also include their datatypes like

value = int | 1
value = double | 0.1

I need only the actual values like value = 1 and value = 0.1 instead of including their datatype. So please suggest some solution so that I can remove the datatype from their values

回答1:

I assume the type of 'int | 1' is String.

Then you can use:

def toValue[A](value: String): A = {
  val valStr = value.split("\\|").last.trim()
  (value.split("\\|").head.trim() match {
    case "double" => valStr.toDouble
    case "int" => valStr.toInt
    case other => valStr
  }).asInstanceOf[A]
}
println(toValue[Int]("int | 1"))
println(toValue[Double]("double | 1.1"))
println(toValue[String]("hello"))

I updated this to a general function. I also saw that | must be escaped.