Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a heterogeneous Array in Scala?

Tags:

arrays

scala

In javascript, we can do:

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

What is the Scala equivalent?

like image 542
Leo Avatar asked Oct 09 '08 05:10

Leo


People also ask

How do you make an array heterogeneous?

var mix = [42, true, “towel”]; Create a heterogeneous array called myArray with at least three elements. The first element should be a number, the second should be a boolean (true or false), and the third should be a string. Feel free to add more elements of any type if you like!

What is heterogeneous array?

A heterogeneous array is an array of objects that differ in their specific class, but all objects derive from or are instances of a common superclass. The common superclass forms the root of the hierarchy of classes that you can combine into heterogeneous arrays.

Is it possible to have heterogeneous data types in arrays?

No, just because int and char can be converted between each other (which for int to char conversion may mean truncation and loss of original value) doesn't mean you store different data types in the array. An array of char is still an array of char elements only.

Can list have different data types in Scala?

You will create Scala List with strings , integers (both 1D & 2D) data types. You will also learn to create a list consisting of both strings and integers.


1 Answers

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

like image 69
Daniel Spiewak Avatar answered Sep 23 '22 13:09

Daniel Spiewak