how to use generics in Scala

风流意气都作罢 提交于 2019-12-06 11:27:22

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 
  }

}

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.

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