How to avoid any mutable things in this builder?

I have a simple Scala class like this:

class FiltersBuilder {

  def build(filter: CommandFilter) = {
    val result = collection.mutable.Map[String, String]()
    if (filter.activity.isDefined) {
      result += ("activity" -> """ some specific expression """)
    } // I well know that manipulating option like this is not recommanded, 
      //it's just for the simplicity of the  example
    if (filter.gender.isDefined) {
      result += ("gender" -> """ some specific expression """)
    }
    result.toMap //in order to return an immutable Map
  }
}

using this class so:

case class CommandFilter(activity: Option[String] = None, gender: Option[String] = None)

The result content depends on the nature of the selected filters and their associated and hardcoded expressions (String).

Is there a way to transform this code snippet by removing this "mutability" of the mutable.Map?

Answers


Map each filter field to a tuple while you add the result to a Seq, then filter out the Nones with flatten finally convert the Seq of tuples to a Map with toMap. For adding more fields to filter you just have to add a new line to the Seq

    def build(filter: CommandFilter) = {
      // map each filter filed to the proper tuple
      // as they are options, map will transform just the Some and let the None as None
      val result = Seq(
        filter.activity.map(value => "activity" -> s""" some specific expression using $value """),
        filter.gender.map(value => "gender" -> s""" some specific expression using $value """)
      ).flatten // flatten will filter out all the Nones
      result.toMap // transform list of tuple to a map
    }

Hope it helps. Gaston.


Since there are at most 2 elements in your Map:

val activity = filter.activity.map(_ => Map("activity" -> "xx"))
val gender = filter.gender.map(_ => Map("gender" -> "xx"))
val empty = Map[String, String]()
activity.getOrElse(empty) ++ gender.getOrElse(empty)

Need Your Help

Do I need a new table for a new language?

mysql database database-design localization

Do I need to create a different table for each new language?

How do I use hitTest:withEvent: to send touches from my nav bar to the underlying view under certain circumstances?

ios objective-c uiview uinavigationcontroller uinavigationbar

Long story short, if the alpha of my UINavigationBar is set to 0, I want all touches to go to the underlying view (which from the perspective of the view controller with the navigation bar would ju...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.