Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Array property in data class error

Tags:

json

kotlin

I'm modelling some JSON - and using the following lines

data class Metadata(
        val id: String,
        val creators: Array<CreatorsModel>
)

along with:

data class CreatorsModel (
        val role: String,
        val name: String
)

However keep seeing the error: Array property in data class error.

Any ideas why this is?

FYI, the JSON looks like:

{
"id": "123",
"creators": [{
   "role": "Author",
    "name": "Marie"
    }
  ]
}
like image 837
userMod2 Avatar asked Jul 29 '19 07:07

userMod2


People also ask

How do I declare an array in data class Kotlin?

There are two ways to define an array in Kotlin. We can use the library function arrayOf() to create an array by passing the values of the elements to the function. Since Array is a class in Kotlin, we can also use the Array constructor to create an array.

Which is correct data class in Kotlin?

There are following conditions for a Kotlin class to be defined as a Data Class: The primary constructor needs to have at least one parameter. All primary constructor parameters need to be marked as val or var. Data classes cannot be abstract, open, sealed, or inner.

How do I inherit from Kotlin data class?

By default, in Kotlin, classes are final and cannot be subclassed. You are only allowed to inherit from abstract classes or classes that are marked with the open keyword. Hence you need to mark the RoundHut class with the open keyword to allow it to be inherited from.


1 Answers

In Kotlin you should aim to use List instead of Array where possible. Array has some JVM implications, and although the compiler will let you, the IDE may prompt you to override equals and hashcode manually. Using List will make things much simpler.

You can find out more about the difference here: Difference between List and Array types in Kotlin

like image 65
Can_of_awe Avatar answered Oct 21 '22 00:10

Can_of_awe