Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force the type of an array when initialized in Scala?

Basically, I have an array like this:

val base_length = Array(
    0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
    64, 80, 96, 112, 128, 160, 192, 224, 0
  );

And when scala sees it, it wants to do this:

base_length: Array[Int] = Array(...)

But I would prefer for it to do this:

base_length: Array[Byte] = Array(...)

I tried:

val base_length = Array[Byte](...)

But scala says:

<console>:4: error: type arguments [Byte] do not conform to method apply's type
parameter bounds [A <: AnyRef]
       val base_length = Array[Byte](1,2,3,4,5)

This seems to me to basically be telling me that the Array constructor wants to figure out what the type of the array is from the arguments. Normally that's awesome, but in this instance I have good reasons for wanting the array elements to be Bytes.

I have looked around for guidance on this, but I don't seem to be able to find anything. Any help would be great!

like image 555
Christopher Avatar asked Aug 27 '09 18:08

Christopher


People also ask

Which type is correct for initializing an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

Can arrays be initialized when they are created?

Initializing ArraysArrays may be initialized when they are declared, just as any other variables. Place the initialization data in curly {} braces following the equals sign. Note the use of commas in the examples below. An array may be partially initialized, by providing fewer data items than the size of the array.

Are arrays immutable in Scala?

The Scala List class holds a sequenced, linear list of items. Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala.


2 Answers

It should be:

C:\prog\>scala
Welcome to Scala version 2.7.5.final (Java HotSpot(TM) Client VM, Java 1.6.0_16).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val gu: Array[Byte] = Array(18, 19, 20)
gu: Array[Byte] = Array(18, 19, 20)

This is not immutable. A Seq would be a step in that direction even if it is only a trait (as Christopher mentions in the comments) adding finite sequences of elements. A Scala List would be immutable.

like image 120
VonC Avatar answered Oct 06 '22 01:10

VonC


Works in Scala 2.8.0:

Welcome to Scala version 2.8.0.r18502-b20090818020152 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_15).
Type in expressions to have them evaluated.
Type :help for more information.

scala> Array[Byte](0, 1, 2)
res0: Array[Byte] = Array(0, 1, 2)
like image 35
Walter Chang Avatar answered Oct 06 '22 01:10

Walter Chang