How do make the JVM recognize a scala.Array[T] as a java array T[] in a polymorphic method call?

330 views Asked by At

The problem can be found in the following code:

      def debug[T](format: String, arg1:T, arg2:Any, args:Any*):T = {
        logger.debug(format, (arg1 :: arg2 :: args.toList).toArray)
        arg1
      }

Since what I pass as the second parameter is an array of Any's, this code should have called SLF4J's debug method

      public void debug(String format, Object[] argArray);

Yet

      public void debug(String format, Object arg);

ends up being called instead.

Let me give an example.

When I call

    debug("The four parameters are {} as String, {} as Integer, {} as String and {} as Integer.", "1", 2, "3", 4)

It logs

    DEBUG - The four parameters are [1, 2, 3, 4] as String, {} as Integer, {} as String and {} as Integer.

Instead of

    DEBUG - The four parameters are 1 as String, 2 as Integer, 3 as String and 4 as Integer.

NOTE1: I assumed the first call would work based on the scala.Array Scaladoc.

Represents polymorphic arrays. Array[T] is Scala's representation for Java's T[].

NOTE2: The code that originated my question can be found at https://github.com/alexmsmartins/UsefullScalaStuff/blob/master/src/main/scala/alexmsmartins/log/LoggerWrapper.scala

This is a small wrapper around slf4j that I use in my Scala projects.

2

There are 2 answers

2
Daniel C. Sobral On BEST ANSWER

You are passing an Array[Any], not an Array[Object]. You could try changing your types from Any to AnyRef (in which case you'll not be able to pass AnyVal's such as Int). You could also call .asInstanceOf[Array[AnyRef]] after .toArray, which, in this one particular case, shouldn't give you trouble because the erasure is the same.

2
oxbow_lakes On

You need to use: (arg1 :: args2 :: args.toList).toSeq: _ * - see how StringLike.format works

Your choice of list creation will cause quite a bit of overhead in terms of object creation for a debug call (certainly it negates any benefit of reducing array creation IMHO)