All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.Country.kt Maven / Gradle / Ivy

There is a newer version: 0.14.0
Show newest version
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)
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy