Scala extend Map (or HashMap) and allow a constructor list of mappings
scala
Solution
class Schema(elems: Tuple2[String, Any]*) extends HashMap[String, Any] {
this ++= elems
}
val mySchema = new Schema("one" -> 1, "two" -> "2")
Explanation:
- `->` is syntactic sugar for a tuple, so the constructor type is a variable number of tuples
- The "normal" way of constructing a Map/HashMap calls the apply method in the companion object which is implemented in GenMapFactory.scala.
Unfortunately, this does not work for an immutable HashMap. As far as I can tell, the only way to "extend" an immutable HashMap is by creating a class that holds an internal reference to one, as described e.g. in this answer to a similar question on SO.
Problem
I have a special Map that will eventually do some consistency checking of values, which are restricted to have special meaning. For now I just want to create a Schema that acts exactly like a Map[String, Any], in particular I'd like to instantiate is with a list of mappings, and not force the types for the Map to be specified, so they are always [String, Any]. So instead of ``` val myMap:Map[String,Any] = Map("one" -> 1, "two" -> "2", ...) ``` I'd like to be able to have: ``` val mySchema:Schema = Schema("one" -> 1, "two" -> "2", ...) ``` Map is a trait so I think I need to extend a class like HashMap ``` class Schema extends HashMap[String, Any] ``` when I instantiate it with a list of initial mappings I get ``` val mySchema = new Schema("one" -> 1, "two" -> "2", ...) Error:(110, 19) too many arguments for constructor Schema: ()drivers.Schema val mySchema = new Schema("one" -> 1, "two" -> "2") ^ ``` There is some magic inside HashMap that is far beyond me to read (it `extends` 1 class `with` 5 traits). But it looks like the constructor's "contents" (a list of mappings?) are passed to something's `initWithContents(contents)` pseudo constructor. Do I need something like that there?