Keep your code clean with algebraic data types (ADTs)

Recently, Daniel Westheide wrote an interesting post about the abuse of the Option type in Scala. You can find it here. I couldn’t agree more with Daniel. This short story is another example that demonstrates how using Option is not always the best option (pun intended). I’m developing an advertising service for a customer using Scala. A simplified version of the Ad data structure is the following: finalcaseclassAd(headline:String,description1:String,description2:String) At some point they told me we need to support, by adding the headline2 field, two types of ad: standard and expanded.

Scala: Seq, Map and Set as functions

Yesterday my mate asked me: “I have a List[String] and a Map[String, Int] and I want a List[Int] where its values are those of the Map whose keys match the List[String] elements, maintaining the order. Should I use pattern matching?“. I know, the sentence is a bit convoluted but the code will make it clear, hopefully. Anyway, I replied: “No, you don’t need pattern matching, you just need this”:

Scala case classes in depth

For this post I’ll consider the following simple case class unless otherwise specified: caseclassPerson(lastname:String,firstname:String,birthYear:Int) Common knowledge about case classes When you declare a case class the Scala compiler does the following for you: Creates a class and its companion object. Implements the apply method that you can use as a factory. This lets you create instances of the class without the new keyword. E.g.: valp=Person("Lacava","Alessandro",1976)// instead of the slightly more verbose: valp=newPerson("Lacava","Alessandro",1976) Prefixes all arguments, in the parameter list, with val.