# 在 Scala 中查詢元素的陣列大小

Suraj P 2023年1月30日 2022年6月7日 Scala Scala Array

## Scala 中的 `length` 和 `size` 運算子

1. `length` 運算子

``````array_name.length
``````

``````object MyClass {

def main(args: Array[String]) {

val myArr = Array("a", "b", Array(1,2,3,4,5,6), "c")
println(myArr.length)

}
}
``````

``````4
``````

1. `size` 運算子

``````array_name.size
``````

``````object MyClass {

def main(args: Array[String]) {

val myArr1 = Array(3, 2, 5, 7)
val fruits = Array("Apple", "Orange",Array("watermelon","tomato"))
val rate : Array[Double] = Array(4.6, 7.8, 9.5, 4.5)

println(myArr1.size)
println(fruits.size)
println(rate.size)

}
}
``````

``````4
3
4
``````

## 在 Scala 中獲取陣列內元素的大小

``````myArr = Array("a", "b" , Array(11,22,33), "c")
``````

``````object MyClass {

def main(args: Array[String]) {

val myArr = Array("a", "b", Array(11,22,33), "c")
println(myArr(2).size)

}
}
``````

``````error: value size is not a member of java.io.Serializable
println(myArr(2).size)
``````

``````object MyClass {

def main(args: Array[String]) {

val myArr = Array("a", "b", Array(11,22,33), "c")

if (myArr(2).isInstanceOf[Array[Int]])
println(myArr(2).asInstanceOf[Array[Int]].size)

}
}
``````

``````3
``````

``````object MyClass {

def main(args: Array[String]) {

val myArr = Array("a", List("tony","stark","hulk","iron man"), "c")

if (myArr(1).isInstanceOf[List[String]])
println(myArr(1).asInstanceOf[List[String]].size)

}
}
``````

``````4
``````
Author: Suraj P

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.