42

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.

2 Answers 2

82
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)
Sign up to request clarification or add additional context in comments.

1 Comment

If the contents of the Array dont matter you can also use new instead of fill: val chars = new Array[Char](256)
43

Use Array.ofDim[Char](256).

See API docs here.

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.