Is there a straightforward way to accesses nested ...
# announcements
t
Is there a straightforward way to accesses nested properties on a data classes? For example:
Copy code
data class Outer(val inner: Inner)
data class Inner(val value: Int)

val state = Outer(Inner(1))

val keyOuter = "inner"
val keyInner = "value"
state[keyOuter][keyInner] // returns 1
Ultimately I'd like to do is specify a 'path' so I can get at the nested value:
dataClass["inner.someValue.value"]
(similar to how lodash does it for javascript objects).
🚫 2
m
You'll have to use reflection to do that. Or use Maps.
t
i hear reflection is quiet costly ... would it be worth converting the data class to a map using something like jackson and then transversing the map? ... unless of course jackson uses reflection internally?!?
m
Reflection can be costly. Depends on the usage scenario. Trade-offs with everything. As to which approach is better, I'd have to know a lot more about what you're trying to achieve to provide any reasonable answer. A Map is generally quite performant, though. I'm not sure how Jackson accomplishes what it does. Haven't dug into the code. Can see if Jackson works w/o kotlin-reflect on your classpath. That will tell you whether it uses reflection or not. Or look at its dependencies. And there maybe something that exists to accomplish what you want. Or a DSL might be better.
t
thanks for the info ... a bit more on what I'm trying to do... I have a state object which can have up to 2 levels of nesting, for example:
Copy code
{
  id: String
  attribute: {
    someAttribute: {
       value: Int
    }
  }
  raw: List<Any>
  ...
}
There are two things I need to do with that object at runtime. The first is being able to get and set nested values based on a variable:
Copy code
state.get("attributes.someAttribute.value")

and

state.set("attributes.someAttribute.value", 10)
and the second requirement is being able to deserialise from a Map (because the object is stored in Firestore)
I started with data classes ... but ran into issues with accessing nested values and deserialisation. I used jackson to get around the deserialstion issue, but now I can figure out how to programmatically access/set nested keys
m
I suspect a Map will be easier to work with. I would only involve Jackson if you need to persist, and retrieve the state externally at some point.
t
👍
thanks for the help
j
i've got a dataframe abstraction that is designed with the ability to use a context backing store to tag metadata about a cell in a table, table being rows and columns; however it is for immutable tables. its not designed for your usecase, but it was designed to host spreadsheet-like formulaic assemblies. arrow optics does close to what you're describing also
t
i'll check it out ty