Play! failing to convert java list to scala list

2019-02-26 04:04发布

问题:

I'm trying to pass a list of strings from my java controller to the scala template.
This is the view code:

public static Result index() {
    List<String> scripts = Arrays.asList(
        "script1.js",
        ...
        "scriptN.js"
    );

    return ok(views.html.index.render(scripts));
}

and this is the tempate code:

@(scripts: List[String])

@main("test page")(scripts) {
    ... html here ...
}

The error I'm getting (in the Typesafe Activation Compile page):

method render in class index cannot be applied to given types;
required: scala.collection.immutable.List
found: java.util.List
reason: actual argument java.util.List cannot be converted to scala.collection.immutable.List by method invocation conversion

Is there a way to solve it without using the java > scala conversions?
I found this question: Play doesn't convert java-list to scala-list which describes a similar situation, though I do not have any templateImports that I'm aware of, I don't even see a Build.scala file...

Any ideas? Thanks!

回答1:

Try below:

import scala.collection.JavaConverters;

public static Result index() {
    List<String> scripts = Arrays.asList(
        "script1.js",
        ...
        "scriptN.js"
    );
    scala.collection.immutable.List<String> ls = JavaConverters.asScalaBufferConverter(scripts).asScala().toList();
    return ok(views.html.index.render(ls));
}


回答2:

try below in your template code :

@import java.util   
@(scripts: util.List[String])