2

In scala I would like to dynamically allocate an array of sequential index values.

In R it is simply maxindex = 10 then array = 1:maxindex which returns 1,2,3,4,5,6,7,8,9,10

Is it possible to do this in scala?

2 Answers 2

3

You should try Range method:

Range(val start : Int, val end : Int, val step : Int)

You could use it like this:

var yourArray = range(1, 10, 1)

That will return an array like you want: 1,2,3,4,5,6,7,8,9,10

Or even more simple:

var yourArraySimpler = 1 until 11

Take a look at the documentation. From the link:

The Range class represents integer values in range [start;end) with non-zero step value step. Sort of acts like a sequence also (supports length and contains).

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

2 Comments

1 until 10 will return 1,2,3,4,5,6,7,8,9, not including 10. You need 1 to 10 to include both numbers
Thanks, this is exactly what I was looking for
2

It is as simple as:

val arr = 1 to 10

which uses an implicit conversion to generate a Range as described in @cacho's answer. Range is a subclass of Seq, but you can call .toArray on it if you specifically need an array.

Comments

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.