What is the correct way to get a subarray in Scala?

nnythm picture nnythm · May 31, 2012 · Viewed 64.9k times · Source

I am trying to get a subarray in scala, and I am a little confused on what the proper way of doing it is. What I would like the most would be something like how you can do it in python:

x = [3, 2, 1]
x[0:2]

but I am fairly certain you cannot do this.

The most obvious way to do it would be to use the Java Arrays util library.

import java.util.Arrays
val start = Array(1, 2, 3)
Arrays.copyOfRange(start, 0, 2)

But it always makes me feel a little dirty to use Java libraries in Scala. The most "scalaic" way I found to do it would be

def main(args: List[String]) {
    val start = Array(1, 2, 3)
    arrayCopy(start, 0, 2)
}
def arrayCopy[A](arr: Array[A], start: Int, end: Int)(implicit manifest: Manifest[A]): Array[A] = {
    val ret = new Array(end - start)
    Array.copy(arr, start, ret, 0, end - start)
    ret
}

but is there a better way?

Answer

paradigmatic picture paradigmatic · May 31, 2012

You can call the slice method:

scala> Array("foo", "hoo", "goo", "ioo", "joo").slice(1, 4)
res6: Array[java.lang.String] = Array(hoo, goo, ioo)

It works like in python.