WestCoastProjects
WestCoastProjects

Reputation: 63172

How to mimic Scala's Map/Array assignment syntax in my own class

Following is a simple map entry assignment:

scala> var myl = mutable.Map[String,String]()
myl: scala.collection.mutable.Map[String,String] = Map()
myl("abc") = "123"

I would like to mimic that assignment structure in my own class that works with mutable Tuple's. Now, "getting" a value from a Map is achieved via the "apply" method:

e.g mutable.HashMap:

  override def apply(key: A): B = {
    val result = findEntry(key)
    if (result eq null) default(key)
    else result.value
  }

I was not however able to find how the map entry is "set" via myMap("myKey") = "myval". A pointer to the Scala source code to do that would be appreciated. Thanks.

Upvotes: 1

Views: 197

Answers (1)

swartzrock
swartzrock

Reputation: 729

The method you want to implement is called update() and takes two parameters, one for the input value passed in parentheses and the other for the assigned value.

class QueryParams {
  var params = ""
  def update(name: String, value: String) { params += s"$name=$value&" }
}

For example:

val p = new QueryParams()
p("q") = "SFO"
p("start") = "10"
p("rows") = "10"
p.params

Upvotes: 3

Related Questions