1

I am new to Kotlin and learning it, I am having a simple data class

data class Country{

    @SerializedName("name")
    val countryName: String?,
    @SerializedName("capital")
    val capital: String?,
    @SerializedName("flagPNG")
    val flag: String?

}

Errors I am facing:

enter image description here]

2 Answers 2

3

Your data class should look like this:

data class Country(

    @SerializedName("name")
    val countryName: String?,
    @SerializedName("capital")
    val capital: String?,
    @SerializedName("flagPNG")
    val flag: String?

)

The difference is, like mentioned in the comments: I used normal parentheses around the fields while you used curly braces

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

4 Comments

it is working but, what is the difference ... both look the same .... waht mistake i made ?
Data classes must have a primary constructor and that primary constructor needs to have at least one parameter!
@Devrath look at how the answer uses normal parentheses around the fields while you used curly braces. Hard to notice at first.
Why it should have at least one parameter?
1

Data Class in Kotiln must have a variable/value parameter in it's constructor declaration.

Official doc states that :

To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements:

  1. The primary constructor needs to have at least one parameter;

  2. All primary constructor parameters need to be marked as val or var;

  3. Data classes cannot be abstract, open, sealed or inner;

  4. (before 1.1) Data classes may only implement interfaces.

So, your data class should be something similar like below :

data class Foo(
    val bar: Any
)

Note: In Kotlin, you can declare class constructor just by placing '()' following by class name to make it as primary constructor.

You class declaration should be something like below :

data class Country(
    @SerializedName("name")
    val countryName: String?,
    @SerializedName("capital")
    val capital: String?,
    @SerializedName("flagPNG")
    val flag: String?
)

Refer here for more info.

Comments

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.