TheGreatCornholio
TheGreatCornholio

Reputation: 1495

Android Kotlin - Serialize mutableList

This is the model I have so far:

import com.google.gson.annotations.SerializedName
import java.io.Serializable


class Memes (
    @SerializedName("id") var id: Long,
    @SerializedName("title") var title: String
)

I need to make it serializible so I can pass it through activities.

When I change it to:

class Memes: Serializable {
    var id: Long,
    var title: String
}

then I get Property getter or setter expected

Upvotes: 0

Views: 1118

Answers (1)

Amin
Amin

Reputation: 3186

In Kotlin you have to instantiate properties with backing field in the construction (getting them from constructor, assigning them some value, or fill them in init blocks). And the only exception is lateinit var. In the first code, you're getting them in constructor. But in second one, they're introduced without being initialize so compiler asks you to either fill them, or convert them to non-backing field by providing getter and setters.

But if you want to make the first code Serializable you have to simply make that implement Serializable like this:

class Memes (
    @SerializedName("id") var id: Long,
    @SerializedName("title") var title: String
) : Serializable

Also it seems that you can turn it into a data class, so I suggest you to do it!

Upvotes: 1

Related Questions