Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 288
nnythm Avatar asked May 31 '12 09:05

nnythm


People also ask

Can Subarray be a single element?

Answer is yes. In C, array is basically a pointer alongside with its length.

How do you add an element to an array in Scala?

Use the concat() Method to Append Elements to an Array in Scala. Use the concat() function to combine two or more arrays. This approach creates a new array rather than altering the current ones. In the concat() method, we can pass more than one array as arguments.


1 Answers

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.

like image 188
paradigmatic Avatar answered Sep 26 '22 15:09

paradigmatic