https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jilles Soeters

09/27/2021, 10:40 PM
🧵 Hey y’all, I’d like to have some dynamic property access with 2 data classes. I imagine this requires some generics but I am not quite sure how to do this in Kotlin. I have an example here https://gist.github.com/jillesme/d1e1af0e0f56f8b5e02d27f9bc17afa5
j

Joffrey

09/27/2021, 10:42 PM
Could you please explain what you're trying to achieve here? (with the actual use case)
j

Jilles Soeters

09/27/2021, 10:44 PM
I have 2 objects. If one key is present in object 2, I want to set the value to that. Otherwise use the value of object 1
j

Joffrey

09/27/2021, 10:46 PM
But what do you mean by a key being present? What are the types of those objects? Are you looking for a reflection-based approach to this?
It seems to me that using maps might be more appropriate in this case, but you didn't explain your actual use case (what you use this for) so it's hard to tell
c

CLOVIS

09/29/2021, 6:01 AM
object2.value ?: object1.value
?
j

Joffrey

09/29/2021, 8:53 AM
If "being present" is about being non-null for objects of the same class, elvis would definitely be the way to go. But I have a feeling that the op is using different classes that may or may not have a given property (at all)