java.util.Arrays.toString method is not overloaded for Strings in Scala

Viewed 318

I've been programming in Scala since 2010 (it's the end of 2017 now) and was shocked today to find out that the java.util.Arrays.toString method is not overloaded for Strings. The following works as expected in Java, but not in Scala.

Java

public class Main {
  public static void main(String[] args) {
    System.out.println(java.util.Arrays.toString(args));
  }
}

Scala

object Main {
  def main(args: Array[String]): Unit = {
    println(java.util.Arrays.toString(args))
  }
}

I know many workarounds for this (so no need to suggest any), but I would assume I wouldn't need one in the first place. I can neither imagine this being a bug (or rather an unfinished feature) for so many years nor can I imagine this behavior being intended.

<console>:12: error: overloaded method value toString with alternatives:
  (x$1: Array[Object])String <and>
  (x$1: Array[Double])String <and>
  (x$1: Array[Float])String <and>
  (x$1: Array[Boolean])String <and>
  (x$1: Array[Byte])String <and>
  (x$1: Array[Char])String <and>
  (x$1: Array[Short])String <and>
  (x$1: Array[Int])String <and>
  (x$1: Array[Long])String
 cannot be applied to (Array[String])

Can someone come up with a reasonable explanation why this is not working? Please don't be cheeky, I see that it's not overloaded for Strings, but there is clearly some hack in Java to make it work, why is there none in Scala?

I found this question, but again it works in Java, why doesn't it in Scala?

PS

Not that it matters, but I got:

  • Scala v2.12.4
  • Java v1.8.0_151
1 Answers

It is actually a bug in java that it works. If you look at the list of candidates, you'll see, that clearly there is no suitable alternative. It ends up calling Array[Object] variant by accident, but that is wrong, becuase Array is invariant in its type parameter (all generic types are invariant in java), so Array[Object] is not a superclass of Array[String].

Related