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
Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.
This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.
Uniform List can be created in Scala using List. fill() method. List. fill() method creates a list and fills it with zero or more copies of an element.
isEmpty function in Scala checks if a list is empty. The list. isEmpty function returns true if the list is empty; otherwise, it returns false .
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 (*
)"
List.range(1,101)
The second argument is exclusive so this produces a list from 1 to 100.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With