object CountryMapper { // A collection to store our country object private val countries: MutableList<Country> = ArrayList() // Get ISO countries, create Country object and // store in the collection. private val isoCountries: Array<String> = Locale.getISOCountries() init { for (country in isoCountries) { val locale = Locale("en", country) val iso: String = locale.isO3Country val code: String = locale.country val name: String = locale.displayCountry if ("" != iso && "" != code && "" != name) { countries.add(Country(iso, code, name)) } } // Sort the country by their name countries.sortWith(CountryComparator()) } fun mapToName(code: String): String { val country = countries.find { it.code == code} country?.let { return it.name } ?: throw Exception("Invalid country code") } /** * Country pojo class. */ private class Country( private val iso: String, val code: String, val name: String ) { override fun toString(): String { return iso + " - " + code + " - " + name.uppercase(Locale.getDefault()) } } /** * CountryComparator class. */ private class CountryComparator : Comparator<Country> { private val comparator: Comparator<Any> init { comparator = Collator.getInstance() } override fun compare(c1: Country, c2: Country): Int { return comparator.compare(c1.name, c2.name) } } }