Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch between Any and String in Scala

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?

like image 417
PunyTitan Avatar asked Aug 30 '25 18:08

PunyTitan


1 Answers

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.

like image 116
dmitry Avatar answered Sep 02 '25 16:09

dmitry