Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 301
WISHY Avatar asked Feb 03 '26 21:02

WISHY


1 Answers

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()
like image 140
Neel Kamath Avatar answered Feb 05 '26 12:02

Neel Kamath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!