0

Considering a simple use case to extract fields of an object in Java reflection:

val fields = this.getClass.getDeclaredFields

it may return incomplete information if generic type is used, but it is short, fast and can handle most cases.

In Scala reflection module (scala.reflect), it appears that such one-liner doesn't exist, the shortest code I know of that can successfully handle this case is:

trait Thing[T <: Thing[T]{

implicit ev: TypeTag[T]

scala.reflect.runtime.universe.typeOf[T].members
}

This uses a redundant F-bounded polymorphism and a TypeTag doesn't carry extra information comparing to a Java class, is there any way to make it shorter, at least as short as Java (which is a very verbose language)?

Thanks a lot for your advice

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
tribbloid
  • 4,026
  • 14
  • 64
  • 103
  • 4
    Well you may just use the **Java** line in **Scala**. On the other hand, why exactly do you need this? `reflection` is usually discouraged in **Scala**, and there are usually safer ways. – Luis Miguel Mejía Suárez Nov 25 '19 at 18:42

1 Answers1

3

I'm not sure that in this specific case

this.getClass.getDeclaredFields

is much shorter than

def fields[T: TypeTag](t: T) = typeOf[T].decls
fields(this)

Anyway you can still use Java reflection in Scala.

Sometimes Scala reflection is more verbose than Java reflection but Scala reflection allows to do things (in Scala terms) that can't be done with Java reflection (for example if corresponding Scala concepts are absent in Java).

It's not true that

TypeTag doesn't carry extra information comparing to a Java class

Types and classes are different concepts. Maybe you meant ClassTags.

To use or not to use F-bounded polymorphism is your choice.

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66