I am creating a request for an api using below class-
class ABCDRequest {
@JsonProperty("name")
private var name: String? = null
@JsonProperty("question")
private var question: String? = null
@JsonProperty("ans")
private var ans: String? = null
fun getName(): String? {
return name
}
fun setName(userName: String?) {
this.name = userName
}
fun getQuestion(): String? {
return question
}
fun setQuestion(ques: String?) {
this.question = ques
}
fun getAns(): String? {
return ans
}
fun setAns(answer: String?) {
this.ans = answer
}
}
I need both setter and getter methods and i need to set values for different fields at different times(not at time time of creation of object for this class).
Is the above way idle or is there any 1 or few lines code for this in kotlin?
1 Answer 1
Use Data Class
which automatically generates field accessors, hashCode(), equals(), toString() and other methods. Read this for a quick introduction.
data class ABCDRequest (
@JsonProperty("name")
private var name: String? = null,
@JsonProperty("question")
private var question: String? = null,
@JsonProperty("ans")
private var ans: String? = null
)
For the official documentation on Data Class
, head over to this link.
-
\$\begingroup\$ I'm starting to like Kotlin. C# should steal some features from it ;-) \$\endgroup\$dfhwze– dfhwze2019年06月30日 05:47:34 +00:00Commented Jun 30, 2019 at 5:47
-
\$\begingroup\$ As wriiten in my question -
i need to set values for different fields at different times(not at time time of creation of object for this class)
.So if i use this way i need to provide all values while creating object of the class in its constructor \$\endgroup\$Android Developer– Android Developer2019年06月30日 07:29:01 +00:00Commented Jun 30, 2019 at 7:29 -
\$\begingroup\$ No, you don't need to provide all values at the time of its creation. Use this data class like this:
var request: ABCDRequest = ABCDRequest()
and when you want to access/set/get the values,request.name = "Android"
orrequest.question?.let { showToast(it.value) }
\$\endgroup\$SaadAAkash– SaadAAkash2019年06月30日 08:02:33 +00:00Commented Jun 30, 2019 at 8:02 -
\$\begingroup\$ @AndroidDeveloper, could you please inform me of the error that you're facing with? Yes I use data classes similarly to fetch, store and use data in android \$\endgroup\$SaadAAkash– SaadAAkash2019年06月30日 08:24:59 +00:00Commented Jun 30, 2019 at 8:24