0

In Java I can do something like:

long[][] foo = new long[10][]
foo[0] = new long[1]
foo[1] = new long[2]

How can I do something similar in Scala?

2
  • val foo = Array.ofDim[Long](2,2) ; foo(0) = Array(1); foo(1) = Array(2) Commented Mar 11, 2018 at 21:10
  • 1
    @mfirry Initially, it's a 2x2 rectangular (not jagged) array, in the end it contains two arrays of length 1 with entries 1 and 2, and lacks eight null entries. It's completely different in every single dimension from what OP wanted. Commented Mar 11, 2018 at 21:13

1 Answer 1

2

You can use Array.ofDim[X](d) to create array of type X and dimension d:

val foo = Array.ofDim[Array[Long]](10)
foo(0) = Array.ofDim[Long](1)
foo(1) = Array.ofDim[Long](2)

or you can use new:

val foo = new Array[Array[Long]](10)
foo(0) = new Array[Long](1)
foo(1) = new Array[Long](2)

to achieve the same.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much! I've spent hours now learning about mutable collections in Scala trying to get my program working, but this is clean, works, and is exactly what I wanted :)
@F.Pizarro but keep in mind that 1) mutable structures are used much less often than in C, for example. Each time you use one, you must make sure that you know why you are using it, and how you avoid that it accidentally escapes to somewhere where it becomes shared mutable state. 2) Arrays are quite low-level constructs (they've always been, also in Java), they require ClassTags and all that to be constructed. Consider using generic collections if you run into such problems with arrays.
Will do. I'm slowly building my mental model of how and why things are done in idiomatic Scala. But I will say it is refreshing to know that when I do want something simple like a jagged array, there's an equally simple way of doing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.