Hreflang Tag Generator — Kotlin source
Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.
This is the Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// hreflang-tag-generator — pure locale-list validation + alternate-link
// emission (SEO/meta trio).
//
// Language: Kotlin (1.9+), standard library only (no external libraries —
// the hreflang grammar is pure, so nothing display-only needs to be linked)
// CosmoDev polyglot showcase port of the `hreflang-tag-generator` tool.
// Ported from src/lib/hreflang.ts — display source, part of CosmoDev's
// polyglot tool pages.
/** One locale/URL pair. Mirrors the TS HreflangRow interface. */
data class HreflangRow(val locale: String, val url: String)
/** The field set for buildHreflang — rows plus an optional x-default URL. */
data class HreflangInput(
val rows: List<HreflangRow> = emptyList(),
val xDefaultUrl: String? = null,
)
/** Diagnostics plus both emitted flavors. On failure ok is false, errors
* lists every row-located problem, and normalized/html/sitemap are empty —
* exactly like the TS result. */
data class HreflangResult(
val ok: Boolean,
val errors: List<String>,
val normalized: List<HreflangRow>,
val html: String,
val sitemap: String,
)
// ll (ISO-639-1 language) — two ASCII letters; ll-CC — two-letter language,
// two-letter region (ISO-3166); http:// or https:// scheme prefix.
private val singleLocaleRe = Regex("^([a-zA-Z]{2})$")
private val regionLocaleRe = Regex("^([a-zA-Z]{2})-([a-zA-Z]{2})$")
private val validUrlRe = Regex("^https?://")
/** Normalize a locale tag to Google's hreflang grammar: ll (ISO-639-1,
* lowercase) or ll-CC (region uppercase, ISO-3166). Case and surrounding
* whitespace are corrected ("en-us" -> "en-US"); anything else is invalid
* and returns null. The Kotlin twin of normalizeLocale() in
* src/lib/hreflang.ts — null stands in for the TS null. */
fun normalizeLocale(raw: String?): String? {
val t = raw?.trim() ?: ""
singleLocaleRe.matchEntire(t)?.let { return it.groupValues[1].lowercase() }
regionLocaleRe.matchEntire(t)?.let {
return it.groupValues[1].lowercase() + "-" + it.groupValues[2].uppercase()
}
return null
}
/** Trim raw and return it when it starts with http:// or https://, otherwise
* null. Mirrors the TS validUrl() helper. */
private fun validUrl(raw: String): String? {
val t = raw.trim()
return if (validUrlRe.containsMatchIn(t)) t else null
}
/** Validate a locale/URL table and emit both hreflang flavors. Invalid input
* collects every error (row-located) and emits empty blocks; valid input
* normalizes locales, preserves row order, and appends x-default last. */
fun buildHreflang(input: HreflangInput): HreflangResult {
val errors = mutableListOf<String>()
val normalized = mutableListOf<HreflangRow>()
val seen = mutableSetOf<String>()
input.rows.forEachIndexed { i, row ->
val n = i + 1
val rawLocale = row.locale ?: ""
val locale = normalizeLocale(rawLocale)
if (locale == null) {
errors.add("Row $n: \"${rawLocale.trim()}\" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).")
return@forEachIndexed
}
if (locale in seen) {
errors.add("Row $n: locale \"$locale\" is already used.")
return@forEachIndexed
}
if (row.url == null || row.url.trim().isEmpty()) {
errors.add("Row $n: URL is required.")
return@forEachIndexed
}
val url = validUrl(row.url)
if (url == null) {
errors.add("Row $n: URL must start with http:// or https://.")
return@forEachIndexed
}
seen.add(locale)
normalized.add(HreflangRow(locale, url))
}
var xDefault: String? = null
val xd = input.xDefaultUrl
if (xd != null && xd.trim().isNotEmpty()) {
xDefault = validUrl(xd)
if (xDefault == null) {
errors.add("x-default: URL must start with http:// or https://.")
}
}
if (errors.isNotEmpty()) {
return HreflangResult(false, errors, emptyList(), "", "")
}
val htmlLines = normalized.map {
"<link rel=\"alternate\" href=\"${it.url}\" hreflang=\"${it.locale}\" />"
}.toMutableList()
val sitemapLines = normalized.map {
" <xhtml:link rel=\"alternate\" hreflang=\"${it.locale}\" href=\"${it.url}\"/>"
}.toMutableList()
if (xDefault != null) {
htmlLines.add("<link rel=\"alternate\" href=\"$xDefault\" hreflang=\"x-default\" />")
sitemapLines.add(" <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"$xDefault\"/>")
}
return HreflangResult(
ok = true,
errors = emptyList(),
normalized = normalized,
html = htmlLines.joinToString("\n"),
sitemap = sitemapLines.joinToString("\n"),
)
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →