Reputation: 877
Is there some way i can iterate over the properties of object and get the name and value both while iterating. I know about the product iterator, but using that I only get the property value not the name of the property at the same time.
Upvotes: 1
Views: 7694
Reputation: 5420
Unless you are building tooling for programmers developing scala, it is very probable that you should be using a Map
instead of an object.
eg:
val myObject: Map[String, Any] =
Map("prop1" -> 1, "prop2" -> "string", "prop3" -> List(1, 2, 3))
for ((key, value) <- myObject) {
println(key, value)
}
If you are building tooling or you can't just swap out the object for a map, you can use reflection as mentioned in the other answers.
Upvotes: 3
Reputation: 38257
Just don't do it!
Use another design: Scala is not PHP or Python or Perl; it's a statically typed functional language with a very expressive type system; such reflection (runtime inspection) is not needed 99.9% of the time and should be avoided for reasons of safety, correctness and performance.
Upvotes: 2
Reputation: 3182
I think, there is no way to do it without using reflection. (See for example here: Getting public fields (and their respective values) of an Instance in Scala/Java)
An other option is using Apache FieldUtils: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/reflect/FieldUtils.html But again it uses reflection in background.
Upvotes: 1