1
\$\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?

\$\endgroup\$
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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I'm starting to like Kotlin. C# should steal some features from it ;-) \$\endgroup\$ – dfhwze Jun 30 '19 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 Jun 30 '19 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\$ – SaadAAkash Jun 30 '19 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 Jun 30 '19 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.