Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - creating a type parametrized array of specified length

If in Scala IDE try the following:

val chars = Array[Char](256) 

it is all fine. But if I do this:

val len = 256 val chars = Array[Char](len) 

it says that it expects a Char instead of len? Why? I expect the behavior to be the same! Why does it think that I want to put that thing in the array instead of specifying it's size? As far as I know, there is no constructor for arrays that takes a single argument to place it inside the array.

like image 303
noncom Avatar asked Feb 23 '12 12:02

noncom


People also ask

How do you create an array of objects in Scala?

Creating an Array and Accessing Its ElementsScala translates the first line in the example above into a call to Array::apply(), defined in the Array companion object. Such a method takes a variable number of values as input and creates an instance of Array[T], where T is the type of the elements.

How do you add an element to an array in Scala?

Use the concat() Method to Append Elements to an Array in Scala. Use the concat() function to combine two or more arrays. This approach creates a new array rather than altering the current ones. In the concat() method, we can pass more than one array as arguments.


2 Answers

val chars = Array[Char](256) 

This works because 256 treated as a Char and it creates one-element array (with code 256)

val len = 256 val chars = Array[Char](len) 

Here len is Int, so it fails

To create array of specified size you need something like this

val chars = Array.fill(256){0} 

where {0} is a function to produce elements

If the contents of the Array don't matter you can also use new instead of fill:

val chars = new Array[Char](256) 
like image 166
Sergey Passichenko Avatar answered Sep 30 '22 19:09

Sergey Passichenko


Use Array.ofDim[Char](256).

See API docs here.

like image 25
missingfaktor Avatar answered Sep 30 '22 20:09

missingfaktor