Generate Getters and Setters in a Koltin Class in Android Studio

Viewed 5136

I am trying to generate Getters and Setters in my Kotlin model class without writing the code manually but the options are not showing up in the Generate Menu in Android Studio.

My Model Class (Kotlin)

import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName

public class EventsRoadSummaryAPINodeModel {

    @SerializedName("road_name")
    @Expose
    var road_name: String? = null

    @SerializedName("locality")
    @Expose
    var locality: String? = null

    @SerializedName("postcode")
    @Expose
    var postcode: String? = null

    @SerializedName("local_government_area")
    @Expose
    var local_government_area: String? = null

    @SerializedName("district")
    @Expose
    var district: String? = null
}

How do I generate getters and setters in a Kotlin class, please?

3 Answers

As per the Kotlin Properties and Fields documentation, each mutable (i.e., var) property has a getter and setter automatically created for it.

Therefore there's no reason to auto generate getters and setters for Kotlin code.

If you have annotations that need to be put on specifically the generated getter, for instance, you can use the @get:Expose syntax.

You can use 'data class' for the same. in data class, you don't need to make the Getter-Setter method. data class automatically create for you

Kotlin Documentation link

Check Google Codelab example for same link

Ok, so poor-mans solution was to paste the Kotlin code below into a java file and reformat the variables to java code. Then the option to generate Getters Setters in the Generate menu appears, in which you can process and generate the Getters Setters.

Temp Java file used to generate Getters Setters

public class EventsRoadSummaryAPINodeModel {

  @SerializedName("road_name")
  @Expose
  String road_name;

  @SerializedName("locality")
  @Expose
  String  locality;

  @SerializedName("postcode")
  @Expose
  String  postcode;

  @SerializedName("local_government_area")
  @Expose
  String  local_government_area;

  @SerializedName("district")
  @Expose
  String  district;

}

I then pasted the generate Getters Setters into my orginal Kotlin class file and let android studio reformt the pasted code to Kotlin format.

Related