简体   繁体   中英

Calling Scala's method from Java with Scala's collection type

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 (ie, 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?

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));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM