2

I'm trying to call a polymorphic method with both varargs and non varargs versions,

var logger = org.slf4j.LoggerFactory.getLogger("foo")  // 1
logger.warn.("{}{}{}", 1, 2, 3)                        // 2
logger.warn.("{}{}{}", Array(1, 2, 3): _*)             // 3
logger.warn.("{}{}{}", Array(1, 2, 3))                 // 4

Line #2 does not compile, giving an “overloaded method value warn with alternatives” error. Line #3 does not compile, giving a “no ': _*' annotation allowed here” error. Line #4 compiles but invokes the wrong method at runtime, it calls Logger.warn(String,Object) when I need to call Logger.warn(String,Object...).

How can I call the correct method from Scala?

Compare this Java code

logger.warn("{}-{}-{}", new Integer[] {1, 2, 3});
// produces 1-2-3

With this Scala

logger.warn("{}-{}-{}", Array(1, 2, 3))
// produces [1, 2, 3]-{}-{}

1 Answer 1

2

Logger.warn(String,Object...) is implemented in the backend by the compiler as Logger.warn(String,Object[]). The Java compiler performs the conversion allowing backward compatibility in the JVM.

In Scala I would imagine you will have to call the method by passing in an array. Does Array(1, 2, 3) produce the same output as Integer[] = {1, 2, 3} in Java?

Additional Info:

This article mentions that you have to convert your Scala array in some cases. Towards the bottom of the article you will see the discussion.

You may have to do Array(1, 2, 3).asInstanceOf[Array[Integer]] as shown in this forum post.

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

3 Comments

No, the Java version does the right thing but the Scala version does not.
@IanPhillips I have added some extra infor to my answer. Does it help?
The article doesn't appear to be correct,m but it pointed me in the right direction so yes, it helped! You have to cast the array as you describe (although to Array[Object] in real code as it's heterogenous) and then expand it out by adding : _* at the end.

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.