Monday, February 15, 2016

A Case for Scala


Here's three interesting things I came across this week with Scala's case idiom.

Backticks

The first is this snippet:

    val b = "b"
    "a" match {
      case b => println("'a' matches b. WTF?")
      case _ => println("no match")
    }

which prints the first line ("... WTF?"). It's a simple gotcha. The b in the case shadows the outside b that equals the string "b". You need to use backticks to make Scala use the outer b (see here) as in:

    "a" match {
      case `b` => println("'a' matches b. WTF?")
      case _   => println("no match") // <-- printed
    }

Regex

The case keyword can also be used in conjunction with regular expressions, for example:

    val hello = "hello.*".r
    val goodbye = "goodbye.*".r

    "goodbye, cruel world" match {
      case hello()   => println("g'day!")
      case goodbye() => println("thanks for all the fish") // this is printed
      case _         => println("no match")
    }

(see here for further information)

Implicits

The third case for the case keyword is no case at all like this code from Elastic4S where the Type Class Pattern is employed. In a nutshell, there is an implementation in the implicit ether that can fulfil our request. In the Elastic4S (1.5.1) code, it looks like this:

  def execute[T, R](t: T)(implicit executable: Executable[T, R]): Future[R] = executable(client, t)

where the executable in question is any Executable that matches the type of our argument of type T. It's a little harder to read (where in the ether is this Executable?) but is much more extensible.


No comments:

Post a Comment