scala – List – apply, indices

One reason why random element selection is less popular for lists than for arrays is that xs(n) takes time proportional to the index n. In fact, apply is simply defined by a combination of drop and head:

xs apply n equals (xs drop n).head

 

The indices method returns a list consisting of all valid indices of a given list:

object Lists_Random extends App{


  val lst=List(1,2,3,4)

println(lst.apply(1))
  println(lst.indices)

}


2
Range(0, 1, 2, 3)

scala.collection.immutable.Range

Leave a comment