Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala create List[Int]

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

like image 746
Lydon Ch Avatar asked Mar 25 '10 09:03

Lydon Ch


People also ask

How do I create a list in Scala?

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.

How do I add values to a list in Scala?

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”.

How do I fill a list in Scala?

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.

How do I return an empty list in Scala?

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 .


2 Answers

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

like image 126
Ben Lings Avatar answered Nov 16 '22 00:11

Ben Lings


List.range(1,101)

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

like image 22
Eastsun Avatar answered Nov 16 '22 00:11

Eastsun