TroyStacer
TroyStacer

Reputation: 33

Scala 2 overload resolution with varargs and Object

I am trying to understand the following behavior in Scala 2.13.10 with respect to method overloading selection.

import scala.collection.JavaConverters._
object Test {
  def func(v: AnyRef*) = { println("varargs") }
  def func(v: Map[String, AnyRef]) = { println("map") }

  def jfunc(v: Object*) = { println("varargs") }
  def jfunc(v: java.util.Map[java.lang.String, Object]) = { println("map") }
}

val strMap: Map[String, String] = Map("test" -> "test")

Test.func("test") \\ varargs
Test.func(strMap) \\ map

Test.jfunc("test") \\ varargs
Test.jfunc(strMap.asJava) \\varargs not map
Test.jfunc(strMap.asInstanceOf[Map[String, AnyRef]].asJava) \\ map

I am wondering why the explicit cast to asInstanceOf[Map[String, AnyRef]] is required to get the correct version of jfunc.

In scala 3.2.2 the explicit cast to asInstanceOf[Map[String, AnyRef]] is not required and the output is

varargs
map
varargs
map
map

Note: I cannot change the method jfunc as it is coming from an external library.

Upvotes: 1

Views: 58

Answers (0)

Related Questions