jaksky
jaksky

Reputation: 3405

Accessing scala immutable Set

as I go along with scala I stumbled upon a code which I fully do not understand its internals. Would be great if some more experienced developer put some shed on that.

Code snippet looks pretty simple:

var cache = Set.empty[String]
...
 if (!cache(url) && depth > 0)
      ...  
      cache += url

question here is cache(url) which evaluates to s: Boolean = true from the context I understand that it works like contains but I may be mistaken. More I am interested how it works internally, e.g. I know that you can access elements of array in the same way as here code mentioned. Set(1,2) gets translated via companion object to Set.apply(1,2). But here I am kind of lost and hence finding the answer in documentation in hard.

Thanks for helping me out

Upvotes: 1

Views: 61

Answers (2)

jaksky
jaksky

Reputation: 3405

Found an explanation in scala doc which states following:

Sets are Iterables that contain no duplicate elements. The operations on sets are summarized in the following table for general sets and in the table after that for mutable sets. They fall into the following categories:

Tests contains, apply, subsetOf. The contains method asks whether a set contains a given element. The apply method for a set is the same as contains, so set(elem) is the same as set contains elem. That means sets can also be used as test functions that return true for the elements they contain. For example:

scala> val fruit = Set("apple", "orange", "peach", "banana")
fruit: scala.collection.immutable.Set[java.lang.String] = Set(apple, orange, peach, banana)
scala> fruit("peach")
res0: Boolean = true
scala> fruit("potato")
res1: Boolean = false

Upvotes: 0

lmm
lmm

Reputation: 17431

It's not translated via the companion object, it's translated to cache.apply(url) (just as Set(1) translates to Set.apply(1) - there's nothing magic about the fact that Set happens to be a companion object, any value works the same). You can see from the scaladoc what apply does on a Set.

Upvotes: 4

Related Questions