Last active
December 5, 2023 19:46
-
-
Save muhammedesadcomert/dfb2e7441896f8494527b1f2ee0c98f1 to your computer and use it in GitHub Desktop.
Firebase DocumentSnapshot conversion for Enum and Long fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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