How to get the country name from the 2-letter country code (alpha-2) in Scala

2 Answers

0 votes
object CountryLookup {

  // ------------------------------------------------------------
  // A static lookup table for O(1) country code → name resolution.
  // Extend as needed; keys must remain uppercase.
  // ------------------------------------------------------------
  val CountryMap: Map[String, String] = Map(
    "CA" -> "Canada",
    "CN" -> "China",
    "DE" -> "Germany",
    "FR" -> "France",
    "GB" -> "United Kingdom",
    "SK" -> "South Korea",
    "IN" -> "India",
    "JP" -> "Japan",
    "US" -> "United States"
  )

  // ------------------------------------------------------------
  // getCountryName
  // Receives a 2‑letter ISO country code and returns the
  // corresponding country name.
  //
  // Input is normalized to uppercase to ensure consistent matching.
  // Returns None if the code is not found.
  // ------------------------------------------------------------
  def getCountryName(alpha2: String): Option[String] = {
    val code = alpha2.trim.toUpperCase
    CountryMap.get(code)
  }

  // ------------------------------------------------------------
  // main
  // Demonstrates the lookup function with several sample codes.
  // ------------------------------------------------------------
  def main(args: Array[String]): Unit = {
    val codes = List("US", "GB", "FR", "JP", "ZZ") // ZZ is intentionally invalid

    codes.foreach { code =>
      getCountryName(code) match {
        case Some(name) => println(s"$code → $name")
        case None       => println(s"$code → (invalid code)")
      }
    }
  }
}


/*
run:

US → United States
GB → United Kingdom
FR → France
JP → Japan
ZZ → (invalid code)

*/

 



answered Sep 19 by avibootz
0 votes
import java.util.Locale

object CountryLookup {
 
  def getCountryName(countryCode: String): Option[String] = {
      // Construct a Locale with the country code
      val locale = new Locale.Builder().setRegion(countryCode.toUpperCase).build()
      
      // getDisplayCountry returns the country name (defaulting to system locale language)
      val countryName = locale.getDisplayCountry(Locale.ENGLISH)
    
      // Returns None if the country code was invalid/unrecognized
      if (countryName.nonEmpty && countryName != countryCode) Some(countryName) else None
    }
 
  // ------------------------------------------------------------
  // main
  // ------------------------------------------------------------
  def main(args: Array[String]): Unit = {
     // Usage examples:
    println(getCountryName("US")) // Some("United States")
    println(getCountryName("JP")) // Some("Japan")
    println(getCountryName("DE")) // Some("Germany")
    println(getCountryName("XX")) // None
  }
}
 
 
/*
run:
 
Some(United States)
Some(Japan)
Some(Germany)
None
 
*/

 



answered Sep 19 by avibootz
...