Scala create List[Int]

Don Ch picture Don Ch · Mar 25, 2010 · Viewed 10.9k times · Source

How can I quickly create a List[Int] that has 1 to 100 in it?

I tried List(0 to 100), but it returns List[Range.Inclusive]

Thanks

Answer

Ben Lings picture Ben Lings · Mar 25, 2010

Try

(0 to 100).toList

The code you tried is creating a list with a single element - the range. You might also be able to do

List(0 to 100:_*)

Edit

The List(...) call takes a variable number of parameters (xs: A*). Unlike varargs in Java, even if you pass a Seq as a parameter (a Range is a Seq), it will still treat it as the first element in the varargs parameter. The :_* says "treat this parameter as the entire varargs Seq, not just the first element".

If you read : A* as "an (:) 'A' (A) repeated (*)", you can think of :_* as "as (:) 'something' (_) repeated (*)"