Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson SerializedName in a Kotlin interface

Tags:

Is there any way to use the gson SerializedName annotation in a Kotlin interface?

interface User {
   @SerializedName("user_id")
   val userId: String?
}

data class MainUser(override val userId: String? = null) : User

I know the annotation can be in the child class, but that's not what I'm looking for as there are many classes extending that interface.

Note 1: Using abstract or open class as a parent of a data class will solve this, but the new problem would be the overrided equals() method in the parent never get called (mainUser1 == mainUser2 never check the equls() method in abstract or open class User )

like image 871
Alireza Sobhani Avatar asked Sep 05 '19 00:09

Alireza Sobhani


2 Answers

I think, that interfaces it's not a good place to have properties (or state). Interfaces very good fits to establish behavior (functions). I'd rather suggest you to use abstract class for your purpose and it will work as you expected.

like image 91
Rinat Suleimanov Avatar answered Nov 02 '22 23:11

Rinat Suleimanov


You can annotate property getter with @get use-site target like this:

interface User {
    @get:SerializedName("user_id")
    val userId: String?
}

data class MainUser(override val userId: String? = null) : User
like image 31
Vladimír Bielený Avatar answered Nov 02 '22 23:11

Vladimír Bielený