Andrew Cassidy
Andrew Cassidy

Reputation: 2998

Random shuffle not working for Range

Scala version 2.10.3 running on java 7

import scala.util.Random
Random.shuffle(0 to 4) // works
Random.shuffle(0 until 4) // doesn't work

:9: error: Cannot construct a collection of type scala.collection.AbstractSeq[Int] with elements of type Int based on a collection of type scala.collection.AbstractSeq[Int].

The error message seems to really only tell me "You can't do that". Anyone have any insight as to why?

Upvotes: 8

Views: 1643

Answers (1)

wingedsubmariner
wingedsubmariner

Reputation: 13667

Scala is inferring the wrong type parameters to shuffle. You can force working ones with:

Random.shuffle[Int, IndexedSeq](0 until 4)

or broken ones with:

Random.shuffle[Int, AbstractSeq](0 to 4)

I don't know why it comes up with the wrong parameters for Range, as returned by until, but the correct ones for Range.Inclusive, as returned by to. Range.Inclusive directly subclasses Range without mixing in any traits, so it shouldn't be treated any differently. This looks like a Scala bug to me.

Upvotes: 7

Related Questions