问题
I have a Java code calling Scala method.
Java side code:
List<String> contexts = Arrays.asList(initialContext);
ContextMessage c = ContextMessage.load(contexts);
Scala side code:
def load(contexts: List[String]) = ...
contexts foreach context =>
In this case, I have scala.collection.immutable.List<String> cannot be applied ...
error message.
I also need to make the type of contexts as general as possible (i.e., Seq) as the load method iterates over the given collection object to process something.
def load(contexts: Seq[String]) = ...
How to solve the two issues?
回答1:
I would just use JavaConversions
and keep my Scala code scalatic.
// Scala code
object ContextMessage {
def load(contexts: Seq[String]) = ???
}
// in your Java code
ContextMessage c = ContextMessage.load(JavaConversions.asScalaBuffer(Arrays.asList(initialContext));
回答2:
In the case Scala calling this method, Implicit conversion between java.util.ArrayList and Seq type can solve this issue easily.
import scala.collection.mutable.ListBuffer
object ContextMessage extends App {
implicit def typeConversion(input: java.util.ArrayList[String]) = {
val res : ListBuffer[String] = new ListBuffer[String]()
for (i <- 0 to input.size - 1) {
// println(input.get(i))
res += input.get(i)
}
res
}
def load(contexts: Seq[String]) = {
contexts foreach { c =>
println(c)
}
}
val x = new java.util.ArrayList[String]()
x.add("A")
x.add("B")
load(x)
}
ContextMessage.main(args)
The result shows:
A
B
来源:https://stackoverflow.com/questions/32107259/calling-scalas-method-from-java-with-scalas-collection-type