Scala

Iterating over a Map in Scala

Posted on by  
Tammo Sminia

Iterating over a map is slightly more complex than over other collections, because a Map is the combination of 2 collections. The keys and the values.

val m: Map[Int, String] = Map(1 -> "a", 2 -> "b")

m.keys    // = Iterable[Int] = Set(1, 2)
m.values  // = Iterable[String] = MapLike("a", "b")

Continue reading →

Chaining Options

Posted on by  
Tammo Sminia

When we have multiple Options and only want to do something when they're all set. In this example we have a property file with multiple configurations for one thing. A host and a port, we only want to use them if they're both set.

//The individual properties
val stubHost: Option[String] = Some("host")
val stubPort: Option[Int] = Some(8090)

//The case class I'll turn them into
case class StubConfig(host: String, port: Int)

Continue reading →

Options with flatMap

Posted on by  
Tammo Sminia

Suppose I have a List of things on which I want to do something that may fail. In this example I have a List of Strings that I want to turn into a List of Integers.

val strings = List("1", "bla", "4")

Continue reading →

Scala Snippet: How to filter a list in Scala

Posted on by  
Arthur Arts

In Scala, filtering and processing collections is easy and elegant. There are many filtermethods available, but the most used will probably the basic filter method. Here's a code example of some filtering on my (ex)camera collection. The filter method will not only work on Lists, but on any Scala collection.

object MyCameraCollection02 {

  case class Camera(brand: String, model: String, sensorType: String, yearBought: Int) {
    override def toString: String =
      s"$brand $model \t\t $sensorType \t($yearBought)"
  }

  def main(args: Array[String]) {
    val canon5dmarkIII = new Camera("Canon", "5D MkIII", "FF", 2013)
    val canon5dmarkII = new Camera("Canon", "5D MkII", "FF", 2009)
    val canon6d = new Camera("Canon", "6D", "FF", 2014)
    val canon550d = new Camera("Canon", "550D", "APS-C", 2010)
    val canon40d = new Camera("Canon", "40D", "APS-C", 2008)
    val canonIXUS330 = new Camera("Canon", "IXUS 330", "1/2.7", 2001)
    val canonIXUSZ90 = new Camera("Canon", "IXUS Z90", "APS-C", 1999)
    val panasonicGM1 = new Camera("Panasonic", "GM1", "M43", 2014)
    val panasonicFZ20 = new Camera("Panasonic", "FZ20", "1/2.5", 2005)
    val sonyrx100 = new Camera("Sony", "DSC-RX100", "1\"", 2013)
    val sonynex5 = new Camera("Sony", "NEX-5", "APS-C", 2011)
    val sonyr1 = new Camera("Sony", "DSC-R1", "APS-C", 2005)

    val myCameras = List(canon5dmarkIII, canon5dmarkII, canon6d, canon550d, canon40d, canonIXUS330, canonIXUSZ90, panasonicGM1, panasonicFZ20, sonyrx100, sonynex5, sonyr1)
    val canonCameras = myCameras filter (_.brand == "Canon") // Every Canon camera I ever owned
    val sonyCameras = myCameras filter (_.brand == "Sony") // Every Sony camera I ever owned
    val pansonicCameras = myCameras filter (_.brand == "Panasonic") // Every Panasonic camera I ever owned


    // apscCamera's only
    val apscCameras = myCameras filter (_.sensorType == "APS-C")
    println("==APS-C camera's owned==")
    apscCameras foreach println
    println()


    // Canon camera's which are not full frame. You can filter, filtered lists.
    val canonNonFF = myCameras filter (_.brand == "Canon") filter (_.sensorType != "FF")
    println("==Non-FF camera's owned==")
    canonNonFF foreach println
    println()

    // Filter by boolean expressions on class properties
    val apsBefore2012 = apscCameras filter (_.yearBought < 2012)
    println("==APS-C camera's bought before 2012 owned==")
    apsBefore2012 foreach println
    println()

    // Filter by combining boolean expressions.
    val ffcamerasBefore2012 = myCameras filter (cam => cam.yearBought < 2012 && cam.sensorType == "FF")
    println("==Every FF Camera I ever owned before 2012==")
    ffcamerasBefore2012 foreach println
    println()
  }
}

Continue reading →

Time libraries in Scala

Posted on by  
Tammo Sminia

Scala has no default way to deal with dates and times. We have a few options. java.util.Date and java.util.Calendar These come included with java, so they may do if you don't need to do much and don't want to add any dependencies. But they're horrible and it's best not to use them. Joda-Time http://www.joda.org/joda-time/ The de facto standard date and time library for Java. nscala-time https://github.com/nscala-time/nscala-time A thin scala layer around Joda-Time. This adds some implicit conversions to make it easier to use, like the + and < operators.

import com.github.nscala_time.time.Imports._
DateTime.now + 2.months // returns org.joda.time.DateTime

Continue reading →

Scala Snippet: Case Class vs plain ordinary Class

Posted on by  
Arthur Arts

In Scala there exist the construct of a 'case class'. According to Martin Odersky this supports you to write a "regular, non-encapsulated data structure". It always seems to be associated with pattern matching. So when to use a case class and when to use a 'plain' class? I found this nice explanation stating: _"Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments. This functional concept allows us to

  • use a compact initialisation syntax (Node(1, Leaf(2), None)))
  • decompose them using pattern matching
  • have equality comparisons implicitly defined

Continue reading →

shadow-left