1

I am trying to solve a (possibly) trivial problem. I would like a nice, concise way to instantiate Array of bytes based on range. So far this works

Array(1 : Byte, 2 : Byte)

but I would like to use sth like

((1: Byte) to (10: Byte)).toArray

this is however Array[Int].

2 Answers 2

3

Range is not generic; it inherits from IndexedSeq[Int], so there's no way to make a "Range of Byte". (Edit: See Daniel C. Sobral's answer for a generic range type!)

When you try ((1: Byte) to (10: Byte)), the Bytes are implicitly converted back to Int again.

How about:

(1 to 10).map(_.toByte).toArray

That will result in two passes over the collection; if that's an issue, a non-strict view will rectify that:

(1 to 10).view.map(_.toByte).toArray
Sign up to request clarification or add additional context in comments.

Comments

3

While Ben James answer is true enough, there is a more generic range for any type T for which there is an Intergral[T]: NumericRange.

import scala.collection.immutable.NumericRange
NumericRange(1: Byte, 10:Byte, 1: Byte).toArray

Another alternative would be mapping the resulting array to byte instead of mapping the range. For example, and using an Array method:

Array.range(1, 10).map(_.toByte)

1 Comment

+1, I noticed NumericRange as I was writing that answer, but didn't investigate enough!

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.