Leo Leo - 29 days ago 11
Scala Question

How do I create a heterogeneous Array in Scala?

In javascript, we can do:

["a string", 10, {x : 1}, function() {}].push("another value");


What is the Scala equivalent?

Answer

Arrays in Scala are very much homogeneous. This is because Scala is a statically typed language. If you really need pseudo-heterogeneous features, you need to use an immutable data structure that is parametrized covariantly (most immutable data structures are). List is the canonical example there, but Vector is also an option. Then you can do something like this:

Vector("a string", 10, Map("x" -> 1), ()=>()) + "another value"

The result will be of type Vector[Any]. Not very useful in terms of static typing, but everything will be in there as promised.

Incidentally, the "literal syntax" for arrays in Scala is as follows:

Array(1, 2, 3, 4)     // => Array[Int] containing [1, 2, 3, 4]

See also: More info on persistent vectors

Comments