0

I want to use multple Constructors like this :

data class MyData<T>(
    val code: String,
    val message: String,
    val data: T? = null,
) {
    constructor(code: String, message: String) : this(code, message, null)
}

and I Use

MyData(code = "-1", message = "Support only application/json Content-Type") // Error :  Not Enough Information To Infer Parameter T
MyData(code = "-1", message = "message", data = "data")

How to Use MyData property 'data' default value is 'null'? ( I want to MyData(code, message) not MyData(code, message) )

1
  • 1
    Your secondary constructor is redundant. By providing a default value for the third parameter, you’ve already created a second constructor that allows you to omit that parameter. Commented Feb 12, 2022 at 16:49

1 Answer 1

1

You pass the type like this:

val obj1 = MyData<String>(code = "-1", message = "Support only application/json Content-Type")

Note that data should probably be a var instead of a val, or you won't be able to change it.

Sign up to request clarification or add additional context in comments.

3 Comments

Immutable classes are a valid and often best design practice.
You said it should probably be a var like it’s a mistake to make the class immutable.
There is a second part in my sentence saying "or you won't be able to change it". Maybe not the best way to put it, I'll give you that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.