Call-by-name:
The method that executes the object returns the object's properties, the object's handle (reference) is passed to the calling method, and all operations are performed through the handle in this
The handle points to the object and does not make a copy. So after the method call is over, the state of this object is changed, unrecoverable call-by-value:
Make a copy of the passed-in parameter, which is done for this copy (the basic type is call by value)
1. The difference between Var,val and Def
First look at the following definition of x, Y, Z:
Class Sheet1 {
val x = 1
var y = 2
def z = 3
}
By compiling the following:
public class Sheet1
{
private final int x = 1;
private int y = 2;
public int x ()
{
return this.x;}
public int y () {return this.y;}
public void Y_$eq (int x$1) {this.y = x$1;}
public int Z () {return 3;
}
}
The difference between the three:
1, Var and Val will do Call-by-value operations, and Val is the final modification, that is, Val can not be changed.
2, Def is to do call-by-name operation.
3, Def and Val are not allowed to change.
Again as follows:
Class Sheet1 {
//Dead loop
def Loop:boolean = loop
//will do Call-by-value, the following statement block live
val x = Loop
var y = loop
//def is Call-by-name, and when it comes to Z, I go to the roots.
def z = Loop
}
2. Call-by-value and call-by-name in function definition
Implementing and with a function is defined as follows:
Def and (X:boolean, y:boolean) =
if (x) Y else false
<pre name= "code" class= "plain" >def Loop:boolean = loop
We use calls and (True,loop), and we find that we are going into a dead loop. The reason is that two parameters are done call-by-value operation, then it has been looking for a loop value, so keep looking down. So it's an indefinite cycle.
Let's turn this function into a call-by-name operation, as follows:
Def and (X:boolean, y: = = Boolean) =
if (x) Y else false
def Loop:boolean = loop
Let's try it: and (false, loop)
Scala> and (false, loop)
Res0:boolean = False<span style= "Font-weight:bold;" >
</span>
Found to work correctly, return False, then we are trying and (true, loop)
Suddenly found itself in a cycle of death. The reason is: The second parameter is Call-by-name, in the beginning, will not go to use it, know the real tune
When you use it, you start to root.
Note: Y is now defined as: y: = = Boolean