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

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 Any array, this code should have called the debug SLF4J method

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

Nonetheless,

  public void debug(String format, Object arg); 

ends up being called instead.

Let me give you an example.

When i call

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

He is recording

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

Instead

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

NOTE 1. I assumed that the first call would work based on scala.Array Scaladoc .

Represents polymorphic arrays. The array [T] is a Scala view for Java T [].

NOTE 2: The code that came up from 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.

+4
source share
2 answers

You are passing Array[Any] , not Array[Object] . You can try changing your types from Any to AnyRef (in this case you cannot pass AnyVal , for example Int ). You can also call .asInstanceOf[Array[AnyRef]] after .toArray , which in this particular case should not bother you, because the erasure is the same.

+2
source

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

Your choice of creating a list will lead to a rather small overhead in terms of creating an object for a debugging call (of course, this negates any advantage of reducing the creation of an IMHO array)

+2
source

Source: https://habr.com/ru/post/1380626/


All Articles