While writing code for RecyclerView to get data I figured out there's a data class in Kotlin.
Following codes are taken from two different projects which are linked above.
@Serializable
data class MarsPhoto(
val id: String,
@SerialName(value = "img_src")
val imgSrc: String
)
class Contacts {
@SerializedName("country")
private val country:String? = null
fun getCountry():String?{
return country
}
}
I know that both classes are doing same job. So what does differentiate them? I also wonder in the MarsPhoto
data class how they can get the id
without declaring SerialName
just the way they did for imgSrc
. (I am just on the way to learning kotlin now, so I'm absolute beginner).
CodePudding user response:
Basically for "data" class the compiler automatically derives the following members from all properties declared in the primary constructor:
equals()/hashCode() pair
toString() of the form "MarsPhoto(id=1, imgSrc=asdf)"
componentN() functions corresponding to the properties in their order of declaration.
copy()
You can read a lot more at enter link description here
On the SerializedName part of your question. if you are dealing with Gson lib by default it is using fields name as "SerializedName". And only if you want to use something different then field name, you can use SerializedName annotation and pass your custom value there. But usually, everybody just writes @SerializedName() with duplication of field names as value for every field.
It's a good idea if you are receiving and Serializing data from server from Json. Because Backend developers can use a bad keys in response, which you don't want to use in your code, so @SerializedName will be the only place where you will have to see this key, and you can name your fields however you like.
CodePudding user response:
@Serializable used to mark class as serializable to disk or like into a file( alternative is Parcel able in android) special useful in case of process death or configuration changes and @SerializedName("country") used for json parsing when u receive the response from server
CodePudding user response:
You get the id
without @SerializedName
because the JSON property field is the same as your variable name, but imgSrc
and img_src
is not. Still, even if they are the same, you should always use @SerializedName
, because your variable names could be converted to random letters during code optimization, and obfuscation.