Scala中的配置生成器

时间:2015-04-14 07:16:06

标签: scala configuration generator configuration-files

假设我在Scala中实现了一个通用组件(就像从this post中提取的那个):

import scala.collection.mutable.Map

sealed trait Language {
  val messages: Map[String, String]
}
class English extends Language {
  val messages: Map[String, String] =
    Map("M01" -> "Ready for cooking - press START",
      "M02" -> "Close the door to start cooking")
}
class French extends Language {
  val messages: Map[String, String] =
    Map("M01" -> "Pret pour la cuisson - presse START",
      "M02" -> "Fermez la porte pour commencer la cuisson")
}
class Lang[A <: Language] {

  private var language: Language = new English

  def chosen(lang: A): Unit = {
    language = lang
  }

  def displayMessage(msg: String): Unit = {
    println(language messages msg) 
  }

}

我关心的是我如何构建配置生成器(我在C ++的术语中引用)来配置这个组件?至少有任何参考?或者另一种方式,我如何使用配置文件来配置它?

1 个答案:

答案 0 :(得分:3)

如果您正在寻找通过配置文件处理翻译的方法,请查看Typesafe Config。在这种特定情况下,您将拥有以下内容:

import scala.collection.mutable.Map
import com.typesafe.config.Config
import scala.collection.JavaConverters._

//within some object/class/...you got it
def loadMessages(config: Config, lang: String): Map[String, String] = config.getObject(lang).asScala map { case (k, v) => k -> v.unwrapped.toString }

您的配置文件将包含以下内容:

translation {     
  english {  
    M01 = "Ready for cooking - press START"  
    M02 = "Close the door to start cooking"  
  }  
  french {  
    M01 = "Pret pour la cuisson - presse START"  
    M02 = "Fermez la porte pour commencer la cuisson"  
  }  
}  

然后加载您的配置文件并获取翻译地图,如下所示:

val config: Config = // load your config file. See Typesafe Config for details

val translationCfg = config.getConfig("translation")

val english = loadMessages(translationCfg, "english")
val french = loadMessages(translationCfg, "french")
...

当然,为了不变性,您可以避免使用可变Mapvar,但这是另一个故事。