Array of objects

Hello,
I’ve often worked with array of objects in the past (Javascript). For example

let ids= [
	{ "plz": 47441,
	  "city": "Moers",
	  "lattitude": 51.4463,
	  "longitude": 6.6396
	},
	{ "plz": 47798,
	  "city": "Krefeld",
	  "lattitude": 51.3311,
	  "longitude": 6.5616
	}
]; 

But I can’t figure out how to do it in Kotlin. Maybe someone can help me.
Zeppi

1 Like

Check out the docs. They are really helpful when learning Kotlin and you can edit and run the code on the site.

Here’s the link to a relevant section on collections, however you really will want to create a class for your object type.


Now for your question, it looks like you’re wanting to create a list of structured data objects. In typed languages, things are a bit different. In Kotlin, we can’t create an arbitrary data structure in the same fashion.

We can create a list of maps, but we’re forced to use the same type for the values like this:

val ids = listOf(
    mapOf(
        "plz" to "47441",
        "city" to "Moers",
        "lattitude" to "51.4463",
        "longitude" to "6.6396",
    ),
    mapOf(
        "plz" to "47798",
        "city" to "Krefeld",
        "lattitude" to "51.3311",
        "longitude" to "6.5616",
    )
)

^ This probably isn’t what you want as lat/lons are forced to be Strings.

You probably should create an ID type or data class. It seems like the “kind” of data that represents an id has a required structure, maybe it could be validated or operated on, etc.

1 Like

Your best shot is to simply declare your own class:

data class ID(
	val plz: Int,
	val city: String,
	val latitude: Double,
	val longitude: Double,
)
	
val ids = arrayOf(
	ID(
		plz = 47441,
		city = "Moers",
		latitude = 51.4463,
		longitude = 6.6396,
	),
	ID(
		plz = 47798,
		city = "Krefeld",
		latitude = 51.3311,
		longitude = 6.5616,
	)
)

It is also possible to use anonymous objects, but it’s not very useful in your case. Kotlin doesn’t support duck typing, so stuff like this won’t work:

val ids = arrayOf(
	object {
		val plz = 47441
		val city = "Moers"
		val latitude = 51.4463
		val longitude = 6.6396
	},
	object {
		val plz = 47798
		val city = "Krefeld"
		val latitude = 51.3311
		val longitude = 6.5616
	}
)

ids[0].city // Unresolved reference: city
2 Likes

That’s a very nice idea. I will do it this way. Thank you.
And how can I write codeblocks here on this site?

My comment was about editing and running the code on the Kotlin Docs site.
You can also use standard markdown in the forum.

In addition to that, you can embed runnable Kotlin in this forum, see this blog post for more: https://blog.jetbrains.com/kotlin/2018/04/embedding-kotlin-playground/#:~:text=Embedded%20Kotlin%20Playground%20works%20on,target%20is%20set%20to%20JVM).

1 Like