19.8. Building Functionality with Types
To put what you’ve learned in this chapter to use, let’s create two
examples. First, you’ll create a “timer” that looks like a 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.
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"
That command returns the results of the find
command it was given, along with the time
it took to run. This can be a helpful way to troubleshoot performance
problems.
You can create a similar timer
method in Scala
to let you run code like this:
val
(
result
,
time
)
=
timer
(
someLongRunningAlgorithm
)
println
(
s
"result: $result, time: $time"
)
In this example, the timer
runs
a method named longRunningAlgorithm
,
and then returns the result from the algorithm, along with the
algorithm’s execution time. You can see how this works by running a
simple example in the REPL:
scala> val (result, time) = timer{ Thread.sleep(500); 1 }
result: Int = 1
time: Double = 500.32
As expected, the code block returns the value 1
, with an execution time of about 500
ms.
The timer
code is surprisingly
simple, and involves the use of a generic type parameter:
def
timer
[
A
](
blockOfCode
:
=>
A
)
=
{
val
startTime
=
System
.
nanoTime
val
result
=
blockOfCode
val
stopTime
=
System
.
nanoTime
val
delta
=
stopTime
-
startTime
(
result
,
delta
/
1000000 ...
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.