how to use generics in Scala

扶醉桌前 提交于 2019-12-07 19:39:40

问题


I have coded this component, to alternate between different languages:

import scala.collection.mutable.Map

sealed trait Language
case object English extends Language {
  val messages: Map[String, String] =
    Map("M01" -> "Ready for cooking - press START",
      "M02" -> "Close the door to start cooking")
}
case object 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 {

  //The default Language
  private var language: Language = English

  def chosen(lang: Language) = language = lang

  def displayMessage(msg: String) = language match {
    case English => English messages msg
    case French => French messages msg 
  }

}

My concern is how to use parameterization to build such a component and then to configure it with different languages given to its parameter?


回答1:


I don't think you really need generic in this case.

Also... your design feels to have something off about it. Anyways... if you think you have a use case for generics... you can do it this way.

Change your trait a liitle

sealed trait Language {
  val messages: Map[ String, String ]
}

Now define your generic class like this,

class Lang[ A <: Language ]( var language: A = English ) {

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

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

}



回答2:


Your code looks simple and clean, I'm not sure generics would improve it.

But, you could move the implementation of Lang into Language. The you would have to pass the language objects as method arguments, perhaps as implicits. The type of the arguments would be T < Language.

I would probably rather stick with your simple lookup table, but change class Lang to object Language, the companion object of the Language trait.



来源:https://stackoverflow.com/questions/29531913/how-to-use-generics-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!