C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Length: This property returns the count of rows (not of all elements) when using nested lists. Each nested List counts as just 1.
ListIndex: We can index within a nested list with the same syntax. And with foreach we can nest lambda expressions.
LambdaScala program that uses 2D list
// Create list of nested lists.
val elements = List(List(20, 30), List(40, 50))
// Print elements.
println(elements)
println(elements.length)
// Access top left element.
val topLeft = elements(0)(0)
println("Top left = " + topLeft)
// Loop over all elements with a foreach call.
elements.foreach(_.foreach(println(_)))
Output
List(List(20, 30), List(40, 50))
2
Top left = 20
20
30
40
50
Finally: We print each item in the nested tuples. This is a representation of 4 rows and 2 columns, a 2D structure.
printlnScala program that uses list, tuple elements
// Create list of tuples.
val elements = List((10, 20), (30, 40), (50, 60))
// Add a tuple to the start of the list.
val modified = (0, 10) :: elements
// Loop over indices in the list.
for (pair <- modified) {
// Get both parts of the tuple.
val left = pair._1
val right = pair._2
// Print parts of the tuple.
println("Left = " + left + "; Right = " + right)
}
Output
Left = 0; Right = 10
Left = 10; Right = 20
Left = 30; Right = 40
Left = 50; Right = 60
Arguments: The two arguments to Array.ofDim are the row count and column count. We must provide a type argument.
Apply: We use the apply() and update() functions to change cells in our 2D array. With apply we access rows—these are 1D arrays.
Update: On the rows, we use update() to change the value of cells. Finally we use nested for-loops to print all Int values.
Scala program that uses Array.ofDim, 2D array
// Create a 2D array of 3 rows and 3 columns.
val numbers = Array.ofDim[Int](3, 3)
// Update first row cells.
val result1 = numbers.apply(0)
result1.update(0, 900)
result1.update(1, 800)
result1.update(2, 700)
// Update second row.
val result2 = numbers.apply(1)
result2.update(0, -1)
// Update third row.
val result3 = numbers.apply(2)
result3.update(0, -2)
// Loop over rows.
for (row <- numbers) {
// Loop over cells in rows.
// ... Display all numbers on lines.
for (cell <- row) {
print(cell)
print(" ")
}
println()
}
Output
900 800 700
-1 0 0
-2 0 0
Tip: Array.ofDim overloads are available. But higher-dimensional arrays tend to be confusing and may harm performance.