Suppose I have list countries of type List[String] and map capitals of type Map[String, String]. Now I would like to write a function
pairs(countries:List[String], capitals:Map[String, String]):Seq[(String, String)]
to return a sequence of pairs (country, capital) and print an error if the capital for some country is not found. What is the best way to do that?
To start with, your
Map[String,String]is already aSeq[(String,String)], you can formalise this a bit by callingtoSeqif you wish:So the problem then boils down to finding countries that aren’t in the map. You have two ways of getting a collection of those countries that are represented.
The
keysmethod will return anIterator[String], whilstkeySetwill return aSet[String]. Let’s favour the latter:Convert that into an error in whatever way you see fit.