Java Reference
In-Depth Information
15.1. Introduction to Scala
This section briefly introduces basic Scala features so you can get a feel for simple Scala
programs. We start with a slightly modified “Hello world” example written in an imperative
style and a functional style. We then look at some data structures that Scala supports—List, Set,
Map, Stream, Tuple, and Option—and compare them to Java 8. Finally, we present traits ,
Scala's replacement for Java's interfaces, which also support inheritance of methods at
object-instantiation time.
15.1.1. Hello beer
Let's look at a simple example so you get a feel for Scala's syntax and features and how they
compare to Java. To change a bit from the classic “Hello world” example, let's bring in some
beer. You want to print the following output on the screen:
Hello 2 bottles of beer
Hello 3 bottles of beer
Hello 4 bottles of beer
Hello 5 bottles of beer
Hello 6 bottles of beer
Imperative-style Scala
Here's how the code to print this output looks in Scala using an imperative style:
Information on how to run this code can be found on the official Scala website. [ 1 ] This program
looks quite similar to what you'd write in Java. It has a structure similar to Java programs: it
consists of one method called main, which takes an array of strings as argument (type
annotations follow the syntax s : String instead of String s like in Java). The main method
doesn't return a value, and so it's not necessary to declare a return type in Scala as you'd have to
do in Java using void.
 
Search WWH ::




Custom Search