Devrath
Devrath

Reputation: 42824

How to use a simple data class in kotlin

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]

Upvotes: 1

Views: 854

Answers (2)

Teetz
Teetz

Reputation: 3765

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

Upvotes: 3

Jeel Vankhede
Jeel Vankhede

Reputation: 12118

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.

Upvotes: 1

Related Questions