Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Class<T> at compile time?

In Java you can write:

Class<SomeClass> foo = SomeClass.class;

I'm playing around with Scala and want a bit more: I want to get a Method (and its generic type) at compile time, like this:

val foo : Method[...] = SomeClass.class.someMethod

or even:

val foo : Method[...] = someObject.class.someMethod

Is there a way to do something like this in Scala?

like image 983
user194860 Avatar asked Feb 23 '23 01:02

user194860


1 Answers

With, perhaps, the sole exception of interop against a Java library that demands Method instances, there should never ever be any need to do this in Scala.

If you need to pass a method around for later invocation; then partially apply it to create a FunctionN instance, pass it via a by-name param, or create it directly as a first-class Function in the first case.

If you need to reflect on the Method so that you can circumvent private visibility, perhaps for testing, then you really should refactor your design to avoid that visibility restriction in the first place.

If you're just exploring Scala, and seeing how concepts compare to java. Or if you're unfortunate enough to be stuck with a bad case of interop, then the equivalent construct to SomeClass.class is classOf[SomeClass]. Hopefully you'll never need it :)

like image 198
Kevin Wright Avatar answered Mar 05 '23 12:03

Kevin Wright