user3293793
user3293793

Reputation: 11

why class Set does not exists in scala?

There are many classes which inherit trait Set. HashSet, TreeSet, etc.

And there's Object(could i call it companion object of trait Set? not in the case of class Set?) Set and trait Set.

It seems to me that just adding one more class "Set" to this list make it seems to be really easy to understand the structure.

is there any reason Class Set should not exists?

Upvotes: 0

Views: 296

Answers (2)

Łukasz
Łukasz

Reputation: 8663

If you just need a set, use Set.apply and you will have a valid set that supports all important operations. You don't need to worry how is it implemented. It is prepared to work well for most use cases.

On the other hand, if performance of certain operations matters for you, create a concrete class for concrete implementation of set, and you will know exactly what you have.

In java you would write:

Set<String> strings = new HashSet<>(Arrays.asList("a", "b"));

in scala you could as well have those types

val strings: Set[String] = HashSet("a", "b")

but you can also use a handy factory if you don't need to worry about the type and simply use

val strings = Set("a", "b")

and nothing is wrong with this, and I don't see how adding another class would help at all. It is normal thing to have an interface/trait and concrete implementations, nothing in the middle is needed nor helpful.

Set.apply is a factory for sets. You can check what is the actual class of resulting object using getClass. This factory creates special, optimized sets for sizes 0-4, for example

scala.collection.immutable.Set$EmptySet$
scala.collection.immutable.Set$Set1
scala.collection.immutable.Set$Set2

for bigger sets it is a hash set, namely scala.collection.immutable.HashSet$HashTrieSet.

Upvotes: 4

robot1208
robot1208

Reputation: 311

In Scala there is no overlap between classes and traits. Classes are implementations that can be instantiated, while traits are independently mixable interfaces. The use of Set.apply gives an object with interface Set and that is all you need to know to use it. I fully understand wanting a concrete type, but that would be unnecessary. The right thing to do here is save it to a val of type Set and use only the interface Set provides.

I know that may not be satisfying, but give it time and the Scala type system will make sense in terms of itself, even if that is different than what Java does.

Upvotes: 1

Related Questions