google-gemini / generative-ai-android

The official Android library for the Google Gemini API
https://ai.google.dev/gemini-api/docs/get-started/tutorial?lang=android
Apache License 2.0
734 stars 160 forks source link

FirstOrdinalSerializer as inline function *TESTED* compatible KMP (no only JVM) #178

Closed karloti closed 5 months ago

karloti commented 5 months ago

Inline Function and Reified Type inline fun <reified T : Enum> firstOrdinalSerializer(): This declares an inline function named firstOrdinalSerializer that takes a reified type parameter T, which must be an enum class (Enum). Inline functions are a Kotlin optimization that can improve performance by avoiding the overhead of function calls. Reified type parameters allow you to access the actual type of T at runtime.

Serializer Implementation object : KSerializer: This creates an anonymous object that implements the KSerializer interface for the enum type T. This interface defines how to serialize and deserialize values of type T.

Descriptor override val descriptor: SerialDescriptor: This property provides a description of the serialized format. Here, it's a PrimitiveSerialDescriptor indicating that the enum will be serialized as a string with the name "EnumSerializer" and a primitive kind of STRING.

Serialization override fun serialize(encoder: Encoder, value: T): This function handles the serialization of an enum value value. It simply encodes the enum's name as a string using encoder.encodeString(value.name).

Deserialization override fun deserialize(decoder: Decoder): T: This function handles deserialization. It decodes a string from the decoder and attempts to find the corresponding enum value using enumValues().firstOrNull { it.name == decodeString }.

Error Handling If the decoded string doesn't match any enum value, a log message is printed to the error log (Log.e) indicating the unknown value and suggesting possible causes (backend update, SDK update, or opening a GitHub issue). In the case of an unknown value, the function returns the first enum value as a fallback (enumValues().first()).

google-cla[bot] commented 5 months ago

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.