Search code examples
scalafunctionreflectionanonymous-function

Create an Anonymous Function with no Parameter in Scala


We know that in Scala reflection, we can invoke a method using

clazz.getDeclaredMethod("method").invoke(instance, parameters)

where the function signature of invoke is Object invoke(Object obj, Object... args).

If we want to make an anonymous function for the above with one parameter, we can write as

val method: Function1[Object, Object] = clazz.getDeclaredMethod("method").invoke(instance, _)

My question is, how to make an anonymous function with NO parameter?

Simply writing clazz.getDeclaredMethod("method").invoke(instance) will call the method without any argument, instead of making it as an anonymous function.


Solution

  • The _ syntax is sugar in the first place and is the same as:

    val method: Function1[Object, Object] = x => clazz.getDeclaredMethod("method").invoke(instance, x)
    

    In order to write a similar function with no parameter:

    val method: Function0[Object] = () => clazz.getDeclaredMethod("method").invoke(instance)