Reputation: 1609
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
Upvotes: 0
Views: 82
Reputation: 10278
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.
Upvotes: 2
Reputation: 1730
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]
Upvotes: 2
Reputation: 29193
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.
Upvotes: 1
Reputation: 12399
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?
Upvotes: 0