3.18. Creating Your Own Control Structures
Problem
You want to define your own control structures to improve the Scala language, simplify your own code, or create a DSL for others to use.
Solution
The creators of the Scala language made a conscious decision not
to implement some keywords in Scala, and instead implemented
functionality through Scala libraries. This was demonstrated in Recipe 3.5,
which showed that although the Scala language doesn’t have break
and continue
keywords, you can achieve the same
functionality through library methods.
As a simple example of creating what appears to be a control
structure, imagine for a moment that for some reason you don’t like the
while
loop and want to create your
own whilst
loop, which you can use
like this:
package
foo
import
com.alvinalexander.controls.Whilst._
object
WhilstDemo
extends
App
{
var
i
=
0
whilst
(
i
<
5
)
{
println
(
i
)
i
+=
1
}
}
To create your own whilst
control structure, define a function named whilst
that takes two parameter lists. The
first parameter list handles the test condition—in this case, i < 5
—and the second
parameter list is the block of code the user wants to run.
You could implement this as a method that’s just a wrapper around
the while
operator:
// 1st attempt
def
whilst
(
testCondition
:
=>
Boolean
)(
codeBlock
:
=>
Unit
)
{
while
(
testCondition
)
{
codeBlock
}
}
But a more interesting approach is to implement the whilst
method without calling while
. This is shown in a complete object
here:
package
com.alvinalexander.controls ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.