Ryan
Ryan

Reputation: 1

Accessing properties of a Kotlin entity

I'm new to Kotlin, so apologies if I'm not articulating concepts correctly. I have an instance of an Entity

[TestEntity(applicationId=1, timestamp=2018-01-24T18:40:30, issueState=MA, product=test, status=sold, paymentMode=VISA, premium=null)]

I am writing a service that is going to take these keys and use them to create the headers of a report. The keys may change depending on the type of report the user is trying to generate, which will have an impact on the Entity that will be instantiated.

I want to be able to iterate over this Entity so that I can create an array to use for the headers. Any thoughts on how I do this?

Upvotes: 0

Views: 306

Answers (1)

Pawel
Pawel

Reputation: 17258

I think the cleanest solution is storing values in a map and delegating properties to it.

Don't think you can otherwise iterate over class fields without some verbose getter chain or ugly reflection shenanigans.

For example here you can access map fields as if they were class fields, but can also easily iterate over map.

data class TestEntity(val map : Map<String, Any>){
    val appId : Int by map
    val timeStamp : Long by map
    (... more fields)
}

Upvotes: 2

Related Questions