scalascala-reflect

Scala Reflection issue on accessing case class attributes


I have been able to get a List of attributes for a case class using scala with Reflection.

import scala.reflect.runtime.universe._

def classAccessors[T: TypeTag]: List[MethodSymbol] = typeOf[T].members.collect {
  case m: MethodSymbol if m.isCaseAccessor => m 
}.toList

case class Z(a1: String, b1: String, id: Integer)
val z = classAccessors[Z]

val res1 = z.map(x => if(x.equals("value id")) "xxx" else x)

However, the .equals does not work, but gives no error -> so I am missing something and I can't google it. Must be something basic.

.replace does not work, how would that go?.

How do I just get a normal List for processing? I note a List[Object]. Did not find anything either in that regard. Mmm. Can someone give an example of not using Reflection?


Solution

  • x has type MethodSymbol. So if(x.equals("value id")) "xxx" else x has type Any (aka Object) because this is the minimal supertype of String and MethodSymbol.

    And x.equals("value id") is always false because MethodSymbol and String are different types.

    Try

    val res1 = z.map(_.toString).map(x => if (x == "value id") "xxx" else x)
    

    or

    val res1 = z.map(_.name).map(x => if (x == "id") "xxx" else x)
    

    Please notice that Java .equals is like Scala ==, Java == is like Scala eq.