Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Array with different data types

Tags:

arrays

scala

any

*as we know that scala array contains data of the same type. But when I declared array as

var a = new Array[Any](3)

I am able to store different data types.

a(0)=5
a(1)="hello"
a(2)=1.5

how is it possible? if it is wrong then what is the option we have in scala to store different data types?*

like image 319
Abhinav Kumar Avatar asked Feb 05 '23 04:02

Abhinav Kumar


1 Answers

The notion of "same type" always depends on a level of generality. In Scala, the level of generality is determined by formal type.

Are 3 and 7 "of the same type"? If we write...

val a : Int = 3
val b : Int = 7

then they of of the same type Int. But, if we define bit-length restricted Int types (which we are very welcome to do in Scala), we might write

val a : Int2 = 3
val b : Int3 = 7

and they no longer appear to be of the same type!

If we define an inheritance hierarchy

trait Animal;
class Dog extends Animal;
class Frog extends Animal;

then do Dog and Frog have the same type? If we write

val d : Dog  = new Dog
val f : Frog = new Frog

then it looks like the answer is no. But if we write

val d : Animal = new Dog
val f : Animal = new Frog

then they look like they do have the same type. Consistent with that, if I declare an array like

val arr : Array[Dog] = Array.ofDim[Dog](5)

then I can't put a frog in it, because a frog is not a dog. But if I declare the a similar array

val arr : Array[Animal] = Array.ofDim[Animal](5)

Then of course both frogs and dogs can go in it, because at the level of generality of Animal, both Frogs and Dogs do have the same type.

In Scala Any is a base type from which all other types derive. So, at a very high level of generality, 5, "hello", and 1.5, all have the same type Any, just as at a high level of generality Frog and Dog have the same type Animal. So there's no problem putting 5, "hello", and 1.5 into an Array[Any].

like image 187
Steve Waldman Avatar answered Feb 15 '23 10:02

Steve Waldman