PS900
PS900

Reputation: 1

Can someone explain the syntax of this Scala function?

def time[R](block: => R): R = {
    val t0 = System.nanoTime()
    val result = block    // call-by-name
    val t1 = System.nanoTime()
    println("Elapsed time: " + (t1 - t0) + "ns")
    result
}

This is a function I found online to measure the time for a block of code to execute in Scala. I don't understand what the [R] before the parameter list is for or what R is - is it just an identifier to represent any data type? I'm relatively new to Scala so any help is appreciated

Upvotes: 0

Views: 198

Answers (1)

George Leung
George Leung

Reputation: 1552

This is just a type parameter, in Java it is <R>, in Scala it is [R].


The similar code in Java would be:

public <R> R time(Supplier<R> block) {
    long t0 = System.nanoTime();
    R result = block.get();
    long t1 = System.nanoTime();
    System.out.println("Elapsed time: " + (t1 - t0) + "ns");
    return result;
}

To use it

System.out.println(time(() -> "hello world"));

will print

Elapsed time: 12345ns
hello world

In Scala the argument type => R is pass-by-name, essentially a function. The benefit of the syntax is that the user does not have to write the lambda.

println(time("hello world"))
// or
println(time {
  Thread.sleep(1)
  123
})

The type parameter R is needed because we want the time function to be generic. R is String in the first example, and Int in the second.

Upvotes: 2

Related Questions