Does the expression use `productElement (i)` when using a case class?

Given the following Scala snippet:

case class Foo(v1: String, v2: Int, v3: Any) def inspect(p: Product) = (0 until p.productArity).foreach(i => println(p.productElement(i))) inspect(Foo("Moin", 77, null)) 

Does this mean that calling inspect() means that reflection is being used (in any way)?

I would like to somehow access the fields of the case class without explicitly accessing them, for example. on foo.v1 , and I would prefer a solution that doesn’t need to be reflected, as I expect this to entail some overhead.

+6
reflection scala case-class field product
source share
1 answer

No reflection will be used for the product item. This is a compiler. Adding a case before the class not only creates a companion object (using the method, etc., see http://www.scala-lang.org/node/258 ), it also extends the class from the product property. The compiler creates implementations of the abstract methods productArity and productElement.

The output of scalac -print Foo.scala shows:

 ... case class Foo extends java.lang.Object with ScalaObject with Product { ... override def productArity(): Int = 3; override def productElement(x$1: Int): java.lang.Object = { <synthetic> val temp6: Int = x$1; (temp6: Int) match { case 0 => { Foo.this.v1() } case 1 => { scala.Int.box(Foo.this.v2()) } case 2 => { Foo.this.v3() } case _ => { throw new java.lang.IndexOutOfBoundsException(scala.Int.box(x$1).toString()) } } }; ... } 

If you want to access fields without reflection, you can use the productElement method from the Product property

 scala> case class Foo(v1: String, v2: Int, v3: Any) defined class Foo scala> val bar = Foo("Moin", 77, null) bar: Foo = Foo(Moin,77,null) scala> bar.productElement(0) res4: Any = Moin scala> bar.productElement(1) res5: Any = 77 scala> bar.productElement(2) res6: Any = null 
+11
source share

All Articles