Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extend / Replicate Scala collections syntax to create your own collection?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

What syntax can I follow to achieve this?

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading