0

I have this invocation from scala class to Java

  private def initSpringActorContext: ConfigurableApplicationContext = {
    val resourceLocations = Array[String]("aopContext.xml", "akkaContext.xml")
    new GenericXmlApplicationContext(resourceLocations))
  }

And the java class expect

 public GenericXmlApplicationContext(String... resourceLocations) {
        this.load(resourceLocations);
        this.refresh();
    }

I´ve tried to cast this with import collection.JavaConverters._

But I cannot make it works with Arrays.

Any suggestion?

2 Answers 2

3

You do not want an Array, but a varargs.

You should do new GenericXmlApplicationContext(resourceLocations: _*)

Sign up to request clarification or add additional context in comments.

2 Comments

Wow that´s magic stuff, what the hell is the scala compiler doing internally there?! Thanks a lot man!
Unlike in java, String* (scala varargs) is not the same as Array[String] in scala. Therefore, we just need to tell the compiler that we want to convert our Array to a varargs by typing it explicitly, which is done with the _* type.
2

GenericXmlApplicationContext constructor accepts varargs as an argument.

You can use : _* syntax to solve the problem.

private def initSpringActorContext: ConfigurableApplicationContext = {
    val resourceLocations = Array[String]("aopContext.xml", "akkaContext.xml")
    new GenericXmlApplicationContext(resourceLocations: _*))
  }

: in this case is a hint to scala compiler about the type of the expression you have.

_* is a type annotation; it basically says accept any value of varargs (_ for any, * for varargs)

Update: As mentioned in the comment, : _* is a fixed syntax; so above deconstruction is only for explanation purposes.

2 Comments

Actually, _* is a fixed syntax, you cannot replace _ by String (see section 4.6.2 of Scala spec).
@CyrilleCorpet good point, I updated my answer to stress that. thnx

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.