0
val Array(direction, value, power, type, zone) = Array(1, 2, 3, 4, 5)

Is there any way to refer Array(1, 2, 3, 4, 5) from some reference that we can use to perform other array operations like iterating array, etc..

i want to use direction, value, power, type, zone as they are more meaningful rather then using arr(0), arr(1), etc.. in addition to doing regular operations on array

1
  • Don't use an Array? Or make its contents into a case class as @irundaia suggests. "Doctor, it hurts when I do that..." Commented Feb 7, 2016 at 8:41

4 Answers 4

2

You can define your array as follows:

val arr @ Array(direction, value, power, t, zone) = Array(1, 2, 3, 4, 5)

This way you can use arr as a normal Array and the other "meaningful" vals.

Note that I changed type by t because the first one is a reserved word of the language.

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

Comments

2

If you want the object to have meaningful accessors to the values it is containing, I would suggest to simply use a case class:

case class MyDataClass(direction: Int, values: Int, power: Int, type: Int, zone: Int)

val d = MyDataClass(1, 2, 3, 4, 5)

val dir = d.direction

To use it as you would with a traditional array, I would add an implicit conversion to Array[Int]

Comments

1

Store the array as normal, then def the elements as indexes into the array.

val array = Array(1,2,3,4,5)
def direction = array(0)
// etc.

This will still work inside of other methods as Scala allows methods in methods.

Comments

0

Am I missing something here? Why not just do

val arr = Array(1, 2, 3, 4, 5)`

and then subscript the individual elements (arr(0), arr(1), etc.) when you need them?

1 Comment

i want to use a, b, c, d, e as they are more meaningful rather then using arr(0), arr(1), etc.. in addition to doing regular opertions on array

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.