Skip to content

Instantly share code, notes, and snippets.

@muhammedesadcomert
Last active December 5, 2023 19:46
Show Gist options
  • Save muhammedesadcomert/dfb2e7441896f8494527b1f2ee0c98f1 to your computer and use it in GitHub Desktop.
Save muhammedesadcomert/dfb2e7441896f8494527b1f2ee0c98f1 to your computer and use it in GitHub Desktop.
Firebase DocumentSnapshot conversion for Enum and Long fields
inline fun <reified T : Any> DocumentSnapshot.toObjectWithConversion(): T? {
val instance = T::class.primaryConstructor?.callBy(
T::class.primaryConstructor!!.parameters.associateWith { parameter ->
val value = this.get(parameter.name.orEmpty())
when {
parameter.type.classifier is KClass<*> && (parameter.type.classifier as KClass<*>).isSubclassOf(Enum::class) -> {
val enumClass = parameter.type.classifier as KClass<Enum<*>>
(value as? String)?.toEnumSafe(enumClass)
}
parameter.type.classifier == Int::class && value is Long -> value.toInt()
else -> value
}
}
)
return instance
}
fun String?.toEnumSafe(enumClass: KClass<Enum<*>>): Enum<*>? {
return enumClass.java.enumConstants?.firstOrNull { it.name.equals(this, ignoreCase = true) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment