Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 2 or more constructors in kotlin

how to add 2 or more constructors ?? i know the use of data class in kotlin, but i am not getting what exactly this keyword is in kotlin and why we have to put anything inside this?

public class Model {
    public String mId, mTitle, mDesc;

    public Model() {

    }

    public Model(String mId, String mTitle, String mDesc) {
        this.mId = mId;
        this.mTitle = mTitle;
        this.mDesc = mDesc;
    }

    public String getmId() {
        return mId;
    }

    public void setmId(String mId) {
        this.mId = mId;
    }

    public String getmTitle() {
        return mTitle;
    }

    public void setmTitle(String mTitle) {
        this.mTitle = mTitle;
    }

    public String getmDesc() {
        return mDesc;
    }

    public void setmDesc(String mDesc) {
        this.mDesc = mDesc;
    }
}

I know kotlin but not that much.

how i changed

data class model_for_single_row (val mId:String,val mTitle:String,val mDesc:String){
    constructor():this()
} 

it gives me error to put something inside this. why we use this here and why we should put, and what we should put?

like image 268
Prabhat kumar Avatar asked Jun 30 '20 07:06

Prabhat kumar


1 Answers

Default value of String in java is null, which isn't the case in Kotlin.

You can make fields nullable and attach their defualt values to null:

data class model_for_single_row(
    val mId: String? = null,
    val mTitle: String? = null,
    val mDesc: String? = null
)

You can call it like:

model_for_single_row()
model_for_single_row("id")
model_for_single_row("id", "title")
model_for_single_row("id", "title", "desc")
model_for_single_row(mTitle = "title")

Parameters not supplied will be null here.

like image 190
Animesh Sahu Avatar answered Oct 12 '22 19:10

Animesh Sahu