The Withprintwriter method shown in the previous section differs from the built-in control structure of the language, such as if and while, where the code with the braces is parameterized. The Withprintwriter method requires a parameter of type PrintWriter. This parameter is displayed in the "writer =>" way:
Withprintwriter (file) {
writer => writer.println (new java.util.Date)
}
However, if you want to implement something more like if or while, there is no value to pass the code between the braces, what do you do? To address this situation, Scala provides Shena parameters.
To give a realistic example, imagine that you need to implement an assertion architecture called Myassert. You can only call it Myassert, not assert, because Scala provides its own assert, which will be described in section 14.1. The Myassert function will enter with a function value and refer to a sign to determine what to do. If the flag bit is set, Myassert calls the Passed-in function and confirms that it returns true. If the sign bit is closed, Myassert will quietly do nothing.
If you don't have Shena parameters, you can write myassert like this:
var assertionsenabled = True
def myassert (predicate: () => Boolean) =
if (assertionsenabled &&!pre Dicate ())
throw new Assertionerror
This definition is correct, but it can be a little ugly to use:
You might want to omit the empty argument list and the => symbol in the function text, written in the following form:
Myassert (5 > 3)//will not be effective because of lack of () =>
The Shena function just happens to fulfill your desires. To implement a Shena function, you define the type of the parameter to begin with => instead of () =>. For example, you can change its type, "() => boolean", "=> boolean", and change the predicate parameter of Myassert to the Shena parameter. Code 9.5 shows how it looks:
def bynameassert (predicate: => Boolean) =
if (assertionsenabled &&!predicate)
throw new Asserti OnError
Code 9.5 using the Shena parameter
Now you can omit the null argument in the attribute that needs to be asserted. The results of using bynameassert seem to be using the built-in control structure:
In the Shena type, an empty argument list, (), is omitted, and it is only allowed in parameters. There is no Shena variable or something called a name segment.