Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the actual class (not abstract and not trait) for Map and Set?

In Scala, map and set literals can be created through, for instance,

val m = Map(1->"a")

And the type of the reference m and the literal are both Map[Int, String].

However, scala documents show that Map is actually a trait, with abstract members that need to be implemented in order to instantiate: scala.collection.Map, scala.collection.immutable.Map, scala.collection.mutable.Map

So my question is: what is the actual, concrete class that the literal Map is based on? Same question above is applicable to Set as well.

like image 840
Yo Hsiao Avatar asked May 23 '16 00:05

Yo Hsiao


People also ask

Why Traits used in Scala?

Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.

How to declare trait in Scala?

In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.

Can Traits have fields Scala?

Traits are like interfaces in Java. But they are more powerful than the interface in Java because in the traits you are allowed to implement the members. Traits can have methods(both abstract and non-abstract), and fields as its members.


1 Answers

You can find the concrete runtime class with getClass:

scala> println(m.getClass)
class scala.collection.immutable.Map$Map1

So it's Map1, a class defined inside the Map companion object. But then we try the same thing on a slightly larger map:

scala> val m2 = Map(1 -> "a", 2 -> "b")
m2: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b)

scala> println(m2.getClass)
class scala.collection.immutable.Map$Map2

Which is a different class. Let's try a map with more elements:

scala> println((0 to 10).map(i => i -> i.toString).toMap.getClass)
class scala.collection.immutable.HashMap$HashTrieMap

Which is yet another class.

In short, the concrete runtime class that you get from Map(...) or toMap is an implementation detail and the vast majority of the time you shouldn't need to worry about it (but when you do, you can check with getClass).

like image 110
Travis Brown Avatar answered Oct 24 '22 15:10

Travis Brown