Supply Structural type in method type parameterization at runtime?
-
07-02-2021 - |
Question
Follow-up to this SO question.
Suppose I have the code
def bar(param: {def foo: Unit}*) = param.foreach(x => x.foo)
This function causes object param
to invoke a method named foo
[EDIT]
I was wondering if the following is possible (with or without reflection)
param
is fixed at compile time, the name of the function (in this casefoo
) is supplied at runtime- both
param
and the name of the functionfoo
are supplied at runtime param
is fixed at compile time, the name of the function, the function parameters, values and return types are supplied at runtime.
I realize Structural typing already uses reflection. So my question is if Scala can take care of it or if I have explicitly use reflection in my code. I think the 3rd one requires reflection for which I can use the ASM library.
Solution
If I understand your question:
- At compile-time, the compiler checks that each
param
has indeed a methodfoo
with the correct signature. - At runtime, reflection is used underneath to call the method
foo
of eachparam
So you don't need to use reflection yourself, but you should keep it mind that reflection will be used at runtime, and could potentially decrease performances.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow