Let’s start with a simple piece of JavaScript code.

I call function f at line 10, where the second and third arguments passed in are a comma expression.

The implementation of function F checks the types of these two arguments, executes the function call if it is a function, and prints its return value, otherwise it prints the value of the expression passed in.

Execute the above code and print the following:

We can see that although the first parameter passed in is true, function F will print only the value of the expression represented by the second parameter y, 5, but the expression represented by the third parameter is also evaluated when function F is called, so the console also outputs Big Calculation2.

If we want to implement what is called “lazy evaluation”, sometimes called “lazy evaluation”, we simply wrap the logic originally written in the expression location in a JavaScript function, as follows:

When f is called again, the arguments y and z are of type function. Therefore, when f is called, the functions represented by y and z are not immediately called, unlike the expressions passed in earlier. Printout:

Let’s see if Scala handles expressions the same way JavaScript does.

Scala is a multi-paradigm programming language designed to integrate the features of object-oriented and functional programming.

Scala runs on a Java virtual machine and is compatible with existing Java programs.

Scala source code is compiled into Java bytecode, so it can run on top of the JVM and can call existing Java class libraries.

In line 5 and line 12 below, I define two Scala functions exp_test1 and exp_test2, respectively. The logic is similar to the previous JavaScript function f.

The second and third arguments accepted by exp_test1 are of type exp1 :=> Unit, which means that an expression needs to be passed in. The return type of this expression is Unit.

The second and third arguments received by exp_test2 are of type exp1() :=> Unit, which means that a function needs to be passed that has no input arguments and whose return type is Unit.

Lines 19 through 25 show various tests for the two functions, printing out:

As you can see, Scala can lazy-evaluate expressions even if the second and third arguments to exp_test1 and exp_test2 are expressions:

The function calls on lines 19 and 20, the expression and function at the third argument position are not evaluated immediately, but lazily.

In the function calls on lines 22 and 23, the expression and function at the second argument position are not evaluated immediately, but lazily.

This small example illustrates that different programming languages may have different implementations of the expression evaluation of function calls: lazy evaluation or just-in-time evaluation.

For more of Jerry’s original technical articles, please follow the public account “Wang Zixi” or scan the following QR code: