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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With