Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random shuffle not working for Range

Tags:

scala

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?

like image 869
Andrew Cassidy Avatar asked May 07 '14 17:05

Andrew Cassidy


1 Answers

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.

like image 159
wingedsubmariner Avatar answered Nov 13 '22 04:11

wingedsubmariner