4
def foo(x : Array[Any]) = println(x.length);
foo(Array[String]("test", "test"));

This code will raise error message:

:6: error: type mismatch;

found   : Array[String]

 required: Array[Any]
       foo(Array[String]("test", "test"))

All classes in Scala directly or indirectly inherit from Any class. So String is Any. Why we cannot pass an Array[String] to the foo method?

PunyTitan
  • 277
  • 1
  • 9
  • 1
    Hint: arrays are *invariant* on type of its argument. `String` is `Any` but `Array[String]` is not `Array[Any]`. Try `def foo[T](x: Array[T])` instead. – dmitry Sep 07 '15 at 13:14
  • 1
    possible duplicate of [Why are Arrays invariant, but Lists covariant?](http://stackoverflow.com/questions/6684493/why-are-arrays-invariant-but-lists-covariant) – cchantep Sep 07 '15 at 22:13
  • Thanks!@dmitry @cchantep – PunyTitan Sep 13 '15 at 15:23

1 Answers1

10

Arrays are invariant on type of its argument, which means that String is Any, but Array[String] is not Array[Any].

def foo[T](x: Array[T]) or def foo(x: Array[_]) will both work.

dmitry
  • 4,989
  • 5
  • 48
  • 72
  • just for curiosity: http://stackoverflow.com/questions/6684493/why-are-arrays-invariant-but-lists-covariant – dmitry Sep 07 '15 at 13:37