0

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 => 

enter image description here

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?

3
  • 1
    What's wrong with just using JavaConversions ? This is the standard way to communicate between Java and Scala for collections Commented Aug 19, 2015 at 23:31
  • 2
    JavaConversions: specifically, asScalaBuffer. Commented Aug 19, 2015 at 23:32
  • BTW using a Java type in a Scala code is wrong to my opinion, especially List because it has a particular meaning and is associated to specific constructs in Scala Commented Aug 19, 2015 at 23:33

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Every time you call your method you create a new list, it's not great. I have not actually checked what the Scala conversions do, but I guess they just define wrappers around Java objects (I will have a look into that)
Yeah, that's the case, these are just wrappes, it's much more efficient : github.com/scala/scala/blob/2.11.x/src/library/scala/collection/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.