Ashish Tuteja
Ashish Tuteja

Reputation: 168

JavaScript bracket notation equivalent in Scala?

JavaScript has bracket notation for objects that allows you to access properties using variables like so:

let x = {name : 'John', age: 21};
let y = 'age'
console.log(x[y])
//21

Is there an equivalent to this for accessing properties in class objects (get all variables in a class instance) in Scala 2?

Upvotes: 3

Views: 125

Answers (2)

zmerr
zmerr

Reputation: 574

Since all case classes extend from Product I wonder if you can call its method productElement(1) for getting its value. I mean using the index of the desired field for getting its value.

case class MyClass(cat: String, dogNum: Int )

val myClass = MyClass("white cat", 2)

println(myClass.productElement(1)) // prints 2
println(myClass.productElement(0)) // prints white cat

also, using pattern matching:

myClass match {
  
 case MyClass(catField, dogNumField) => 
  println(catField)  // prints white cat
  println(dogNumField) //prints 2
  
}

as yet another way for achieving what might be looking for:

myClass.productIterator.foreach(member => println(member))

Update

"Since Scala 2.13 you can also retrieve the names of the attributes of a Product." – Gaël J

So you can write:

val productSize = myClass.productArity


for (elementNum <- 0 to productSize-1){
   
   println(myClass.productElementName(elementNum) + ": " + myClass.productElement(elementNum))

}

which prints:

cat: white cat
dogNum: 2

Upvotes: 1

Zircoz
Zircoz

Reputation: 512

I suspect that this can be done with Java's Reflection API. I haven't tried it myself yet so you might need to play with it to find the right implementation.

These might help:

Upvotes: 0

Related Questions