2

Say for example I have the following object...

val ob = Thread.currentThread().getStackTrace()[2]

...and I want to select a property from this via a dynamic variable. ob.<property> would work normally but what if I didn't know <property> at compile time?

Is it possible to run something like ob[<property:str>] (as is the case in javascript, python etc) in kotlin?

3
  • 1
    This is called reflection. There are many questions about this subject already on here. kotlinlang.org/docs/reference/reflection.html Commented Aug 8, 2020 at 15:37
  • Also: it's best to avoid using reflection unless there's no other way. It's slow, fragile (as many errors which would otherwise be spotted at compile-time must be handled at run-time), hard to read, and hard to refactor. It's great for compile-time tools, frameworks, plug-ins, &c; but for general-purpose coding there's usually a better approach. Commented Aug 8, 2020 at 15:44
  • 1
    you can have the expected objects implement a common interface Commented Aug 8, 2020 at 19:40

1 Answer 1

1

Yes it is, there is a nice library kpropmap. We use it on production because we just need to have a Map<String, *>, but I wouldn't recommend using it for accessing fields.

https://github.com/rocketraman/kpropmap https://mvnrepository.com/artifact/com.github.rocketraman/kpropmap

After adding a dependency you can just write

val map = propMapOf(obj)
val name = map["name"]

However it'd much better if you were able to cast the obj to some known type and access the property statically

(obj as? SomeInterface)?.name
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.