WISHY
WISHY

Reputation: 11999

Data class inheritance in kotlin?

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?

Upvotes: 2

Views: 9028

Answers (1)

Neel Kamath
Neel Kamath

Reputation: 1266

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()

Upvotes: 10

Related Questions