18

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

2 Answers 2

38

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 (*)"

2
  • 1
    Thanks, what does :_* do in List(0 to 100:_*) ?
    – Lydon Ch
    Commented Mar 25, 2010 at 10:01
  • Hmm. This returns type List[scala.collection.immutable.Range.Inclusive] for me. @Eastsun seems to return the correct type.
    – cevaris
    Commented Sep 10, 2014 at 16:18
13
List.range(1,101)

The second argument is exclusive so this produces a list from 1 to 100.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.