DEFINE SOME FUNCTIONS
Now that you've worked with Scala variables, you'll probably want to write some functions. Here's how you do that in Scala
scala> def max(x: Int, y: Int): Int = {
if (x > y) x
else y
}
max: (x: Int, y: Int)Int
Sometimes the Scala compiler will require you to specify the result type of a function. If the function is recursive, for example, you must explicitly specify the function's result type. In the case of max,however, you may leave the result type off and the compiler will infer it.Also, if a function consists of just one statement, you can optionally leave off the curly braces. Thus, you could alternatively write
the max function like this:
scala> def max(x: Int, y: Int) = if (x > y) x else y
max: (x: Int, y: Int)Int
Once you have defined a function, you can call it by name, as in:
scala> max(3, 5)
res4: Int = 5
When you define the greet() function, the interpreter will respond with greet: ()Unit. "greet" is, of course, the name of the function. The empty parentheses indicate the function takes no parameters. And Unit is greet's result type. A result type of Unit indicates the function returns no interesting value. Scala's Unit type is similar to Java's void type; in fact, every void-returning method in Java is mapped to a Unit-returning method in Scala. Methods with the result type of Unit, therefore, are only executed for their side effects. In the case of greet(), the side effect is a friendly greeting printed to the standard output.
WRITE SOME SCALA SCRIPTS
Although Scala is designed to help programmers build very large-scale systems, it also scales down nicely to scripting. A script is just a sequence of statements in a file that will be executed sequentially.
Put this into a file named hello.scala:
println("Hello, world, from a script!")
then run:
$ scala hello.scala
And you should get yet another greeting:
Hello, world, from a script!
Command line arguments to a Scala script are available via a Scala array named args. In Scala, arrays are zero based, and you access an element by specifying an index in parentheses. So the first element in
a Scala array named steps is steps(0), not steps[0], as in Java. To try this out, type the following into a new file named helloarg.scala:
// Say hello to the first argument
println("Hello, " + args(0) + "!")
then run:
$ scala helloarg.scala planet
In this command, "planet" is passed as a command line argument, which is accessed in the script as args(0). Thus, you should see:
Hello, planet!
Note that this script included a comment. The Scala compiler will ignore characters between// and the next end of line and any characters between /* and */. This example also showsStrings being concatenated with the + operator. This works as you'd expect. The expression"Hello, " + "world!" will result in the string "Hello, world!".
LOOP WITH WHILE; DECIDE WITH IF
To try out a while, type the following into a file named printargs.scala:
var i = 0
while (i < args.length) {
if (i != 0)
print(" ")
print(args(i))
i += 1
}
println()
Scala the semicolons are very often optional, giving some welcome relief to your right little finger. If you had been in a more verbose mood, therefore, you could have written the echoargs.scala script as follows:
var i = 0;
while (i < args.length) {
if (i != 0) {
print(" ");
}
print(args(i));
i += 1;
}
println();
ITERATE WITH FOREACH AND FOR
A far more concise way to print each command line argument is:
args.foreach(arg => println(arg))
In the previous example, the Scala interpreter infers the type of arg to be String, since String is the element type of the array on which you're calling foreach. If you'd prefer to be more explicit, you can mention the type name. But when you do, you'll need to wrap the argument portion in parentheses (which is the normal form of the syntax anyway):
args.foreach((arg: String) => println(arg))
Running this script has the same behavior as the previous one.
If you're in the mood for more conciseness instead of more explicitness, you can take advantage of a special shorthand in Scala. If a function literal consists of one statement that takes a single argument, you need not explicitly name and specify the argument. Thus, the following code also works:
args.foreach(println)
To summarize, the syntax for a function literal is a list of named parameters, in parentheses, a right arrow, and then the body of the function. This syntax is illustrated in Figure 2.2.

Now, by this point you may be wondering what happened to those trusty for loops you have been accustomed to using in imperative languages, such as Java or C. In an effort to guide you in a functional direction, only a functional relative of the imperative for (called a forexpression) is available in Scala. While you won't see their full power and expressiveness until you reach (or peek ahead to) Section 7.3, we'll give you a glimpse here. In a new file named forargs.scala, type the following:
for (arg <- args)
println(arg)
The parentheses after the "for" contain arg <- args. To the right of the <- symbol is the familiar args array. To the left of <- is "arg", the name of a val, not a var. (Because it is always a val, you just write "arg" by itself, not "val arg".) Although arg may seem to be a var, because it will get a new value on each iteration, it really is a val: arg can't be reassigned inside the body of the for expression.Instead, for each element of the args array, a new arg val will be created and initialized to the element value, and the body of the for will be executed.
If you run the forargs.scala script with the command:
$ scala forargs.scala for arg in args
You'll see:
for
arg
in
args
Scala's for expression can do much more than this, but this example is enough to get you started. We'll show you more about for in Section 7.3 and Chapter 23.
网友评论