Java Reference
In-Depth Information
1 See http://www.scala-lang.org/documentation/getting-started.html .
Note
In general, nonrecursive method declarations in Scala don't need an explicit return type because
Scala can infer it for you.
Before we look at the body of the main method, we need to discuss the object declaration. After
all, in Java you have to declare the method main within a class. The declaration object
introduces a singleton object: it declares a class Beer and instantiates it at the same time. Only
one instance is ever created. This is the first example of a classical design pattern (the singleton
design pattern) implemented as a language feature—free to use out of the box! In addition, you
can view methods within an object declaration as being declared as static; this is why the
signature of the main method isn't explicitly declared as static.
Let's now look at the body of main. It also looks similar to Java, but statements don't need to
end with a semicolon (it's optional). The body consists of a while loop, which increments a
mutable variable, n. For each new value of n you print a string on the screen using the
predefined method println. The println line showcases another feature available in Scala: string
interpolation. String interpolation allows you to embed variables and expressions directly in
string literals. In the previous code you can use the variable n directly in the string literal s"Hello
${n} bottles of beer". Prepending the string with the interpolator s provides that magic.
Normally in Java you'd have to do an explicit concatenation such as "Hello " + n + " bottles of
beer".
Functional-style Scala
But what can Scala really offer after all our talk about functional-style programming throughout
this topic? The previous code can be written in a more functional-style form as follows in Java 8:
public class Foo {
public static void main(String[] args) {
IntStream.rangeClosed(2, 6)
.forEach(n -> System.out.println("Hello " + n +
Search WWH ::




Custom Search