1

Consider the following snippet:

val mapOfArrays = (0 to 10).map{
  Array(1, 2)
}

I was expecting the output to be of type List[Array[Int]], but it is not. Any ideas?

enter image description here

1
  • 3
    You can write this as List.fill(11)(Array(1,2)). Commented Oct 24, 2015 at 23:01

2 Answers 2

7

Running it in the REPL shows that it actually raises an exception:

scala> val mapOfArrays = (0 to 10).map{
     |   Array(1, 2)
     | }
java.lang.ArrayIndexOutOfBoundsException: 2
  at scala.collection.mutable.WrappedArray$ofInt.apply$mcII$sp(WrappedArray.scala:155)
  at scala.collection.mutable.WrappedArray$ofInt.apply(WrappedArray.scala:155)
  at scala.collection.mutable.WrappedArray$ofInt.apply(WrappedArray.scala:152)
  at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
  at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
  at scala.collection.immutable.Range.foreach(Range.scala:166)
  at scala.collection.TraversableLike$class.map(TraversableLike.scala:245)
  at scala.collection.AbstractTraversable.map(Traversable.scala:104)
  ... 37 elided

This is because the code is equivalent to:

val mapOfArrays = (0 to 10).map{
  Array(1, 2).apply
}

or the more verbose

val mapOfArrays = (0 to 10).map{ x => 
  Array(1, 2).apply(x)
}

which is indeed an IndexedSeq[Int].


The .apply method off Array returns the element at the given index, which throws an ArrayIndexOutOfBoundsException when x (from (0 to 10)) reachs 2.

Modifying the code so that it doesn't throw an exception:

scala> val mapOfArrays = (0 to 3).map{ Array(1, 2, 3, 4, 5) }
mapOfArrays: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4)

I'm guessing you intended to write this instead:

scala> val mapOfArrays = (0 to 10).map{ x =>
         Array(1, 2)
       }
mapOfArrays: scala.collection.immutable.IndexedSeq[Array[Int]] = Vector(Array(1, 2), Array(1, 2), Array(1, 2), Array(1, 2), Array(1, 2), Array(1, 2), Array(1, 2), Array(1, 2), Array(1, 2), Array(1, 2), Array(1, 2))
Sign up to request clarification or add additional context in comments.

Comments

3

The map call is expecting a function as a parameter, but you are passing an Array of two values. It will then try to call apply on this array with each element of the range.

I believe this is what you intended.

val mapOfArrays = (0 to 10).map(item => Array(1,2))

1 Comment

An array is a Function1[Int, T] (more precisely: a Seq is a PartialFunction[Int, T]) from its indices to its values, which is why the OP's code "works" in the first place.

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.