Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Why does Seq.contains take an Any argument, instead of an argument of the sequence type?

Tags:

So for example why does List(1,2,3,4).contains("wtf") even compile? Wouldn't it be nice if the compiler rejected this?

like image 962
Seth Tisue Avatar asked Sep 09 '10 17:09

Seth Tisue


People also ask

How does Scala seq work?

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.

What is the difference between list and SEQ in Scala?

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.

What is an indexed seq?

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.

What is a SEQ in spark?

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.


1 Answers

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 ==)                       ^ 
like image 150
Daniel C. Sobral Avatar answered Oct 05 '22 00:10

Daniel C. Sobral