Search code examples
scalanashorn

How to create a Scala Seq[String]() from within nashorn?


I need to create a Seq() object for feeding it into another Scala object from within nashorn. The class is imported into nashorn via

var seqClass = Java.type("scala.collection.Seq");

and the object creation looks like:

var seq = new seqClass();

But when creating the object for it, I get a TypeError:

TypeError: Can not create new object with constructor scala.collection.Seq with the passed arguments; they do not match any of its method signatures. in <eval> at line number 13

I suspect the generic class for the Seq() is missing, but I cannot figure out how to add it to the above code.


Solution

  • I have no experience with Nashorn, but Scala Seqs and other collections are created by calling companion methods instead of constructors. Given my understanding, it should be something like

    val seqCompanion = Java.type("scala.collection.immutable.Seq$").MODULE$
    seqCompanion.empty() 
    

    EDIT: I expected seqCompanion.apply(str1, str2, ...) to work for non-empty sequences, but after checking it, the JVM signature of Seq$.apply is public scala.collection.GenTraversable scala.collection.generic.GenericCompanion.apply(scala.collection.Seq) so it won't. You could do it by writing a Scala method which accepts an Array[A] and produces Seq[A] directly and calling it as above:

    // scala
    object SeqToArray { def a2s[A](a: Array[A]) = a.toSeq }
    
    // Nashorn
    Java.type("SeqToArray$").MODULE$.a2s([str1, ...])