In javascript, we can do:
["a string", 10, {x : 1}, function() {}].push("another value");
What is the Scala equivalent?
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!
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.
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.
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.
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
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