Friday, April 5, 2013

7 languages in 7 weeks: Scala day 2

Day two is all about collections. Forcing the typical Java developer (me) to think about iteration in a different way.

Exercise 1 is to take a List of strings and add up the number of characters using the fold left function. There is a very similar example in the book so I think the author is just checking you are paying attention:

Exercise 2 introduces you to Traits by asking you to develop a trait that has a method which censors a string by substituting words in a string. The words to substitute and what to substitute them with should be stored in a Map.


Then create a version that loads the substitutions from a file:

I chose to extend the trait and populate the alternatives field. Spending all my days writing Java what I ended up producing looks very alien to me. It works (I think) something like this:

  • Open and read a file using the library method fromFile
  • Get the lines of the file one by one using getLines
  • Map each like to an Array by splitting the like with the = sign (the file is key value pairs like a Java properties file)
  • Map the array to a tuple then turn it into a list
  • Construct a map from the List of tuples
And done! Looks a lot nicer than it sounds! The full source code is available on my github.


No comments: