Scala: How to build control structures with types and call-by-name parameters

Table of Contents1 - Example 1: Creating a Timer2 - Example 2: Writing Your Own “Try” Classes3 - The Scala 2.10 Try classes

(This article is an excerpt from the Scala Cookbook.)

To put what you’ve learned in this chapter to use, let’s create two examples. First, you’ll create a timer method that looks like a Scala control structure, and works like the Unix time command. Second, you’ll create another control structure that works like the Scala 2.10 Try/Success/Failure classes.

Back to top

Example 1: Creating a Timer

On Unix systems you can run a time command (timex on some systems) to see how long commands take to execute:

$ time find . -name "*.scala"

A simple Scala call-by-name example

Here’s a simple Scala call-by-name example. I’ll show the normal approach to writing a method and passing in a parameter, and then show a call-by-name (pass by name) example.

1) A “normal” Scala method (call-by-value)

Here I show how to pass a parameter to a method “normally,” i.e., call by value: