2

While reading a book on Scala i stumbled upon the following code. Am unable to segregate the code into the function, parameters, variables.

 val feeds = Map("Andy Hunt"   -> "blog.toolshed.com",  
                "Dave Thomas" -> "pragdave.me",     
                "NFJS"        -> "nofluffjuststuff.com/blog")

val fiterName = feeds filter { element =>   
  val (key, value) = element    
  (key startsWith "D") && (value contains "pragprog")   
}

Can some one explain me the code step by step?

0

1 Answer 1

6

feeds is a Map[String, String] which maps a person to a blog.

Then that map is iterates with a filter, which attempts to filter any author which starts with the capital letter D and his value contains the word "pragprog".

When you filter on a Map, you get a tuple which has the key as the first element and the value as the second element. Using round brackets, it looks like this:

val filterName = feeds.filter(element => {
   val (key, value) = element    
   key.startsWith("D") && value.contains("pragprog")
})

Note that filter by itself is a higher order function, it takes another function as input. This function takes an argument of type A, which in our case is a tuple (String, String), and produces a boolean which indicates if the element matches the condition or not. Inside the filter, they used tuple deconstruction:

val (key, value) = element    

Which takes a Tuple2[String, String] and calls it's unapply method, allowing you to access the components of the tuple by name, and not via ._1 and _.2

Sign up to request clarification or add additional context in comments.

4 Comments

Well i understood that looking at the code but what am wondering is? As per the spec filter takes a predicate (String,String)=>Boolean. With that in mind what does val (key,value) = element mean? then on what value the boolean expression (key startsWith "D") && (value contains "pragprog") is invoked?
@Gurupraveen Updated the answer to reflect your question.
One more question, what if i don't want to use tuple deconstruction? how would i achieve same results?
@Gurupraveen element._1.startsWith("D") && element._2.contains("pragprog")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.