View Category

Put a internationalizate of HelloWorld program

Set locale to "es" (spanish) and provide a program that changes outputs ("Helloworld") depending of locale.

In pseudocode:

Void main () {

Locale.set("es")

print.translate("Helloworld, Locale.get)

}
scala
import scala.collection.mutable

object SolutionXX {

// START

class I18N(s: String) {
def translate = {
Locale.current match {
case None => s
case Some(loc) => loc.translate(s).getOrElse(s)
}
}
}

implicit def stringToI18N(s: String) = new I18N(s)

class Locale(val name: String, map: Map[String, String]) {
Locale.registerLocale(this)

def translate(s: String) = map.get(s)
}

object Locale {
var current: Option[Locale] = None
var locales: mutable.Map[String, Locale] = mutable.Map()

def registerLocale(locale: Locale) {
locales += (locale.name -> locale)
//NOTE : here we could check locale translation completeness against others and prints whose entries are missing
}

def set(locale: String) {
current = locales.get(locale)
}
}

val helloworld = "Hello World!";
//NOTE :: just read out properties files in maps below
val en = new Locale("en", Map(helloworld -> "Hello World!"))
val fr = new Locale("fr", Map(helloworld -> "Bonjour le Monde !"))
val es = new Locale("es", Map(helloworld -> "¡Hola Mundo!"))

def main(args: Array[String]) {
def printIn(locale: Option[String]) {
locale match {
case None =>
case Some(l) => Locale.set(l)
}
println(helloworld.translate)
}

printIn(None)
printIn(Some("en"))
printIn(Some("fr"))
printIn(Some("es"))
printIn(Some("alien"))
}


// END
}