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 is yes. In C, array is basically a pointer alongside with its length.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With