Scala: Arrays Cheat Sheet

One Dimensional Array

This array contains only one row for storing the values. All values of this array are stored contiguously starting from 0 to the array size.

Syntax:

var arrayname = new Array[datatype](size)

Multidimensional Arrays

Multidimensional arrays contain more than one row to store the values. Scala has a method Array.ofDim to create Multidimensional arrays in Scala.

Syntax:

var array_name = Array.ofDim[ArrayType](N, M)
 or  
var array_name = Array(Array(elements), Array(elements)

Here N is number of rows and M is number of Columns. 

Scala Array Methods

MethodsDescription
def apply( x: T, xs: T* ): Array[T]Creates an array of T objects, where T can be Unit, Double, Float, Long, Int, Char, Short, Byte, Boolean.
def concat[T]( xss: Array[T]* ): Array[T]Concatenates all arrays into a single array.
def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): UnitCopy one array to another. Equivalent to Java’s System.arraycopy(src, srcPos, dest, destPos, length).
def empty[T]: Array[T]Returns an array of length 0
def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]Returns an array containing repeated applications of a function to start value.
def fill[T]( n: Int )(elem: => T): Array[T]Returns an array that contains the results of some element computation a number of times.
def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]Returns a two-dimensional array that contains the results of some element computation a number of times.
def iterate[T]( start: T, len: Int)( f: (T) => T ): Array[T]Returns an array containing repeated applications of a function to start value.
def ofDim[T]( n1: Int ): Array[T]Creates an array with given dimensions.
def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]Creates a 2-dimensional array
def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]Creates a 3-dimensional array
def range( start: Int, end: Int, step: Int ): Array[Int]Returns an array containing equally spaced values in some integer interval.
def range( start: Int, end: Int ): Array[Int]Returns an array containing a sequence of increasing integers in a range.
def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]Returns an array containing values of a given function over a range of integer values starting from 0.
def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]Returns a two-dimensional array containing values of a given function over ranges of integer values starting from 0.

Leave a Reply

Your email address will not be published. Required fields are marked *