2

I have 2 model class in Java, where one extends the other

@UseStag
public class GenericMessages extends NavigationLocalizationMap implements Serializable {
@SerializedName("loginCtaText")
@Expose
String loginCtaText;
@SerializedName("forgotPasswordCtaText")
@Expose
String forgotPasswordCtaText;

public String getLoginCtaText() {
    return loginCtaText;
}

public String getForgotPasswordCtaText() {
    return forgotPasswordCtaText;
}
}

NavigationLocalizationMap class

public class NavigationLocalizationMap implements Serializable {

@SerializedName("localizationMap")
@Expose
public HashMap<String, LocalizationResult> localizationMap;

@SerializedName("geoTargetedPageIds")
@Expose
public HashMap<String, String> geoTargetedPageIdsMap;

@SerializedName("pageId")
@Expose
public String pageId;

public HashMap<String, LocalizationResult> getLocalizationMap() {
    return localizationMap;
}

public void setLocalizationMap(HashMap<String, LocalizationResult> localizationMap) {
    this.localizationMap = localizationMap;
}

public HashMap<String, String> getGeoTargetedPageIdsMap() {
    return geoTargetedPageIdsMap;
}

public void setGeoTargetedPageIdsMap(HashMap<String, String> geoTargetedPageIdsMap) {
    this.geoTargetedPageIdsMap = geoTargetedPageIdsMap;
}

public void setPageId(String pageId) {
    this.pageId = pageId;
}

public String getPageId() {
    String countryCode = !TextUtils.isEmpty(CommonUtils.getCountryCode()) ? CommonUtils.getCountryCode() : Utils.getCountryCode();
    String _pageId = null;
    if (getGeoTargetedPageIdsMap() != null) {
        _pageId = getGeoTargetedPageIdsMap().get(countryCode);
        if (_pageId == null) {
            _pageId = getGeoTargetedPageIdsMap().get("default");
        }
    }
    if (_pageId == null) {
        _pageId = pageId;
    }
    return _pageId;
}

}

So I am converting the current code base to Kotlin If I create them to data class I can't have inheritance. Is there alternate to achieve it?

WISHY
  • 11,067
  • 25
  • 105
  • 197
  • 3
    Consider reading this post [https://stackoverflow.com/questions/26444145/extend-data-class-in-kotlin](https://stackoverflow.com/questions/26444145/extend-data-class-in-kotlin) – Abhay Agarwal Jun 11 '20 at 07:06
  • 1
    Does this answer your question? [Extend data class in Kotlin](https://stackoverflow.com/questions/26444145/extend-data-class-in-kotlin) – Vadzim Jan 20 '22 at 21:08

1 Answers1

9

Use an interface

interface Human {
    val name: String
}

data class Woman(override val name: String) : Human

data class Mom(override val name: String, val numberOfChildren: Int) : Human

Use a sealed class

sealed class Human {
    abstract val name: String
}

data class Woman(override val name: String) : Human()

data class Mom(override val name: String, val numberOfChildren: Int) : Human()
Neel Kamath
  • 1,188
  • 16
  • 34