2
\$\begingroup\$

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?

asked Jun 29, 2019 at 18:57
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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.

answered Jun 30, 2019 at 5:42
\$\endgroup\$
4
  • \$\begingroup\$ I'm starting to like Kotlin. C# should steal some features from it ;-) \$\endgroup\$ Commented 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\$ Commented 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" or request.question?.let { showToast(it.value) } \$\endgroup\$ Commented 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\$ Commented Jun 30, 2019 at 8:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.