In Kotlin, it's recommended to use data classes as the representation for your entities. In our case, we did not use data classes since we extended a common class containing the attributes shared between the Note and Todo classes.
We recommend the use of data classes since it can significantly simplify your work routine, especially if you are using these entities in backend communication.
It's not rare that we have a need for classes that have only one purpose--holding the data. The benefit of using data classes is that some functionality that is often used along with its purpose is automatically provided. As you probably already know how to define a data class, you have to do something like this:
data class Entity(val param1: String, val param2: String)
For the data class, the compiler automatically provides you with the following:
- The equals() and hashCode() methods
- The toString() method in human readable form,
Entity(param1=Something, param2=Something) - The copy() method for the cloning
All data classes must satisfy the following:
- The primary constructor needs to have at least one parameter
- All primary constructor parameters need to be marked as val or var
- Data classes cannot be abstract, open, sealed, or inner
Let's introduce some data classes! Since we plan to use a remote backend instance, it will require some authentication. We will create new entities (data classes) for the data we pass during the authentication process, and for the result of the authentication. Create a new package called api. Then, create a new data class called UserLoginRequest as follows:
package com.journaler.api data class UserLoginRequest( val username: String, val password: String )
UserLoginRequest class will contain our authentication credentials. The API call will return a JSON that will be deserialized into the JournalerApiToken data class as follows:
package com.journaler.api import com.google.gson.annotations.SerializedName data class JournalerApiToken( @SerializedName("id_token") val token: String, val expires: Long )
Pay attention that we used the annotation to tell Gson that the token field will be obtained from the id_token field in JSON.