commonMain.Country.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fluid-stdlib-macosx64 Show documentation
Show all versions of fluid-stdlib-macosx64 Show documentation
Potentially useful Kotlin standard library additions
package io.fluidsonic.stdlib
import io.fluidsonic.stdlib.Country_Static.allCountryCodes
import kotlinx.serialization.*
import kotlinx.serialization.internal.*
@Serializable(with = CountrySerializer::class)
/*inline*/ class Country private constructor(
val code: String
) {
init {
freeze()
}
override fun equals(other: Any?) =
other === this || (other is Country && code == other.code)
override fun hashCode() =
code.hashCode()
val name
get() = name(Locale.englishInUnitedStates)
override fun toString() =
name
companion object {
val all: Collection = allCountryCodes.map { Country(it.toUpperCase()) }
private val allByCode = all.associateBy(Country::code)
fun byCode(code: String) =
allByCode[code.toUpperCase()]
}
}
expect fun Country.name(locale: Locale): String
internal expect object Country_Static {
val allCountryCodes: Set
}
@Serializer(forClass = Country::class)
internal object CountrySerializer : KSerializer {
override val descriptor = StringDescriptor.withName("io.fluidsonic.stdlib.Country")
override fun deserialize(decoder: Decoder) =
decoder.decodeString().let { code ->
Country.byCode(code) ?: throw SerializationException("Unknown country code: $code")
}
override fun serialize(encoder: Encoder, obj: Country) {
encoder.encodeString(obj.code)
}
}