by-name

This is a page from my book, Functional Programming, Simplified

How to Use By-Name Parameters in Scala

“Call me, call me by my name, or call me by number.”

Chesney Hawkes, “The One and Only”

Introduction

In previous lessons I showed how to pass a function into another function. I showed how to do that (the syntax), and I also showed why to do that (to easily pass in new algorithms).

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: