Home > Software design >  Extend / Replicate Scala collections syntax to create your own collection?
Extend / Replicate Scala collections syntax to create your own collection?

Time:11-21

I want to build a map however I want to discard all keys with empty values as shown below:

@tailrec
  def safeFiltersMap(
                          map: Map[String, String],
                          accumulator: Map[String,String] = Map.empty): Map[String, String] = {
    if(map.isEmpty) return accumulator

    val curr = map.head
    val (key, value) = curr
    safeFiltersMap(
      map.tail,
      if(value.nonEmpty) accumulator   (key->value)
      else accumulator
    )
  }

Now this is fine however I need to use it like this:

val safeMap = safeFiltersMap(Map("a"->"b","c"->"d"))

whereas I want to use it like the way we instantiate a map:

val safeMap = safeFiltersMap("a"->"b","c"->"d")

What syntax can I follow to achieve this?

CodePudding user response:

The -> syntax isn't a special syntax in Scala. It's actually just a fancy way of constructing a 2-tuple. So you can write your own functions that take 2-tuples as well. You don't need to define a new Map type. You just need a function that filters the existing one.

def safeFiltersMap(args: (String, String)*): Map[String, String] =
    Map(args: _*).filter {
      result => {
        val (_, value) = result
        value.nonEmpty
      }
    }

Then call using

safeFiltersMap("a"->"b","c"->"d")
  • Related