In scala, how can I find the size of an array element
When you create an array using the following literal
val aaa = Array("a", "b", Array(1, 2, 3), "c")
Since the type of the elements are different, the array aaa
type is created with java.io.Serializable
aaa: Array[java.io.Serializable] = Array(a, b, Array(1, 2, 3), c)
So when you refer back the 2nd element, the type of the reference will be of Serializable
and there is no size property in it. So we need to explicity typecast/convert the 2nd element to Array using asInstanceOf. As shown below
if (aaa(2).isInstanceOf[Array[Int]])
aaa(2).asInstanceOf[Array[Int]].size
Most common type for your declaration is serializable
val aaa = Array("a", "b", Array(1, 2, 3), "c")
Array[java.io.Serializable]
If you want to use it with size, you can explicitly define:
val aaa: Array[Seq[Any]] = Array("a", "b", Array(1, 2, 3), "c")
all Strings will be converted to Sequences of Chars in this case.