So for example why does List(1,2,3,4).contains("wtf")
even compile? Wouldn't it be nice if the compiler rejected this?
Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.
Indexed sequences support constant-time or near constant-time element access and length computation. They are defined in terms of abstract methods apply for indexing and length . Indexed sequences do not add any new methods to Seq , but promise efficient implementations of random access patterns.
Seq is a trait which represents indexed sequences that are guaranteed immutable. You can access elements by using their indexes. It maintains insertion order of elements. Sequences support a number of methods to find occurrences of elements or subsequences.
Lots of interesting answers, but here's my own theory: if contains
did not receive an Any
, then Seq
could not be co-variant.
See, for instance, Set
, which is not co-variant and whose contains
take an A
instead of an Any
.
The reasons for that is left as an exercise to the reader. ;-) But here is a hint:
scala> class Container[+A](elements: A*) { | def contains(what: A): Boolean = elements exists (what ==) | } <console>:7: error: covariant type A occurs in contravariant position in type A of value what def contains(what: A): Boolean = elements exists (what ==) ^
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