Useful Scala Snippets

Written by Andrew Conner · Apr 9, 2015

There’s a few classes and functions I’ve collected over the past few years that I find incredibly useful with day-to-day Scala development.

Get the calling stack

Often, during development, it’s useful to find out “who is calling this?” If this happens to be called many times or concurrently, it’s difficult to use a debugger. Here’s a snippet that will print out (ideally) the relevant part of the call stack.

def printStack() = {
  println(new Exception().getStackTrace.filter{
    _.getClassName.contains("com.yourpackage")
  }.map { l => 
    l.getClassName + "." + l.getMethodName + "(" + l.getFileName + ":" + l.getLineNumber + ")"
  }.take(6).mkString("\n"))
}

A better ???

??? is a great shortcut to get your code to compile while working on the implementation of functions (it just throws a NotImplementedError, which Scala allows to type check to any type). It’s sometimes useful to find out what type is being inferred naturally. Enter ?!?:

private type ATypeTag[+A] = TypeTag[A @uncheckedVariance]
def ?!?[A](implicit tag: ATypeTag[A]): A =
  throw new NotImplementedError(s"unimplemented value of type ${tag.tpe}")

Immediately mapping a Future

Often, in SoA / “microservice” projects, it’s common to call a remote service asynchronously, get back the result (in JSON, msgpack, protobuf, etc) and serialize it for consumption. If you’re not careful, it’s easy to context switch quite a bit.

implicit class FutureExtensionOps[A](x: => Future[A]) {
  private val immediate = new scala.concurrent.ExecutionContext {
    override def execute(runnable: Runnable): Unit = {
      try { runnable.run() } catch {
        case t: Throwable => reportFailure(t)
      }
    }
    override def reportFailure(t: Throwable): Unit = t.printStackTrace()
    override def prepare(): scala.concurrent.ExecutionContext = this
  }
  def imap[S](g: A => S): Future[S] = {
    x.map(g)(ExecutionContext.immediate)
  }
}

This immediately executes the result in the same thread as the future. Keep anything in this ExecutionContext as fast as possible.

Helpful operators

implicit class AnyExtensionOps[A](val x: A) extends AnyVal {
  // expr |> updateA |> updateB |> save
  def |>[B](f: A => B): B = f(x)

  // func(a) tap println
  def tap(f: A => Unit): A = {
    f(x)
    x
  }
}

The forward pipe operator |> is useful when making updates to objects, especially if the updates may be conditional. Borrowed from Ruby, tap lets you side effect on any value, which is mostly useful for logging or during development.

Folding your Trys

Try doesn’t have a fold, which is useful when you’re able to elegantly handle exceptions.

implicit class TryExtensionOps[A](val x: Try[A]) extends AnyVal {
  def fold[B](f: A => B, g: Throwable => B): B = x match {
    case Success(t) => f(t)
    case Failure(t) => g(t)
  }
}

Hope you find these helpful. Contact me with other useful Scala snippets, and I’ll add them.


I value your thoughts and feedback. Reach out by email or Twitter.