Home > Blockchain >  Scala Reflection issue on accessing case class attributes
Scala Reflection issue on accessing case class attributes

Time:01-31

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?

CodePudding user response:

This val z = classAccessors[Z].map(_.toString()) solved it. Not sure about all the facts behind it, but List[Object] went to List[String].

CodePudding user response:

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.

  • Related