Cyril N.
Cyril N.

Reputation: 39859

Is it possible to call a scala method passed as a parameter in a Java method?

I'm working with Play framework via a Java project and I'd like to pass my templates (Scala functions) as parameters to one of my Java method.

I'd like to do something like this :

public static Result ok(ScalaFunction template, Object obj) {
    // do some work, then :
    return ok(template.render(obj));
}

MyClass.ok(views.html.mytemplate, SomeModel.find.findList());

Of course, this doesn't work. I supposed views.html.mytemplate is a class, so I switched to views.html.mytemplate.class and public static Result ok(Class template, Object obj) in my method, but I can't call render on it.

Is it possible to do something like this ?

If someone knows a better alternative, what I'm trying to achieve is either return a JSON representation of obj if the Accept header is "application/json", or the compiled template (given in first parameter) if the Accept header is "text/html".

Upvotes: 3

Views: 152

Answers (1)

DaniHolonia
DaniHolonia

Reputation: 66

Say your Scala function takes and returns an Object, hence of type Function1<Object, Object> then your Java method should look like this:

public Result ok(Function1<Object, Object> template, Object obj) {
    // do some work, then:
    return ok(template.render(obj));
}

Upvotes: 4

Related Questions