If you want to do it manually in an imperative style:
def rowsTest() {
val array = Array(
Array(9, 11, 4, 89),
Array(7, 62, 34, 2),
Array(3, 4, 5, 12),
Array(13, 4, 5, 12),
Array(3, 24, 5, 12),
Array(3, 4, 35, 12)
)
def rows: Iterator[Iterator[Int]] = {
new Iterator[Iterator[Int]] {
private var rowIndex = 0
def hasNext: Boolean = rowIndex < 6
def next: Iterator[Int] = {
val rowIdx = rowIndex
val rowIterator = new Iterator[Int] {
private var columnIndex = 0
def next: Int = {
val p = array(rowIdx)(columnIndex)
columnIndex += 1
println("ColIndex = " + columnIndex.toString)
p
}
def hasNext: Boolean = columnIndex < 4
}
rowIndex += 1
println("RowIndex = " + rowIndex.toString)
rowIterator
}
}
}
for (row <- rows; elem <- row)
println(elem)
}
but
val rows: Iterator[Iterator[Int]] = array.iterator.map(_.iterator)
ziggystar is even better, because its work with non-rectangular 2D arrays is also more specific and "scalaish".
source
share