Skip to content

Instantly share code, notes, and snippets.

@bhurling
Last active October 23, 2024 14:59
Show Gist options
  • Save bhurling/c955c778f7a0765aaffd9214b12b3963 to your computer and use it in GitHub Desktop.
Save bhurling/c955c778f7a0765aaffd9214b12b3963 to your computer and use it in GitHub Desktop.
Kotlin way of converting country codes to emoji flags
import java.util.Locale
fun countryCodeToEmojiFlag(countryCode: String) {
return countryCode
.toUpperCase(Locale.US)
.map { char ->
Character.codePointAt("$char", 0) - 0x41 + 0x1F1E6
}
.map { codePoint ->
Character.toChars(codePoint)
}
.joinToString(separator = "") { charArray ->
String(charArray)
}
}
@tillkuhn
Copy link

Thanks, very useful!
Two small corrections: Declare return type : String, and use uppercase() since toUpperCase() has been deprecated.

fun countryCodeToEmojiFlag(countryCode: String): String {
    return countryCode
        .uppercase(Locale.US)
        .map { char ->
          Character.codePointAt("$char", 0) - 0x41 + 0x1F1E6
        }
        .map { codePoint ->
          Character.toChars(codePoint)
        }
        .joinToString(separator = "") { charArray ->
          String(charArray)
        }
}

@ferazoguerrero
Copy link

ferazoguerrero commented Jun 17, 2024

Thanks for your contribution. Usage:

countryCodeToEmojiFlag("CO") // --> 🇨🇴

(do not use the country code phone number, like me hehe)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment