1

I'm trying to create a firestore document in Kotlin, and I have this data class:

    val profileDoc = Profile(
        username = queriedUsername,
        device_id = listOf<String>(),
        img = profile_img,
        isDeleted = false,
        hasInitialisedTags = false,
        isGridViewSelected = false,
        isAddButtonHintHidden = false,
        isTaskTypeHintHidden = false,
        newSpacesBadgeNumber = 0,
        savedSpacesBadgeNumber = 0
    )

And then I'm converting it to a hashMapOf:

    val ProfileData = hashMapOf(
        "device_id" to profileDoc.device_id,
        "email" to email,
        "username" to queriedUsername,
        "img" to profile_img,
        "isDeleted" to profileDoc.isDeleted,
        "hasInitialisedTags" to profileDoc.hasInitialisedTags,
        "isGridViewSelected" to profileDoc.isGridViewSelected,
        "isAddButtonHintHidden" to profileDoc.isAddButtonHintHidden,
        "isTaskTypeHintHidden" to profileDoc.isTaskTypeHintHidden,
        "newSpacesBadgeNumber" to profileDoc.newSpacesBadgeNumber,
        "savedSpacesBadgeNumber" to profileDoc.savedSpacesBadgeNumber
    )

I'm wondering if there's a way to convert it without having to repeat the same code?

I've tried using kotlin.serialization, but it doesn't seem to work. Android Studio doesn't know where to import ExperimentalSerializationApi or anything else. I've added the implementation and it built properly, but it still says:

Unresolved reference: ExperimentalSerializationApi

So is there another way?

Heron. F
  • 232
  • 3
  • 13

1 Answers1

2

Try the Kotlin Reflection library.

First, you must add kotlin-reflect in your depedencies

  depedencies {
implementation "org.jetbrains.kotlin:kotlin-reflect"
}

This could help you to learn how to use kotlin-reflect to convert Data class to HashMap https://www.baeldung.com/kotlin/data-class-to-map

https://code.luasoftware.com/tutorials/kotlin/kotlin-convert-data-class-to-map/

I hope these resources help you to solve your problem

KayraOz
  • 31
  • 5