Book Image

Scala for Java Developers

By : Thomas Alexandre
Book Image

Scala for Java Developers

By: Thomas Alexandre

Overview of this book

Table of Contents (19 chapters)
Scala for Java Developers
Credits
Foreword
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Differences in style between Java and Scala code


If you are going to refactor or rewrite Java code into Scala code, there are a number of style differences that are useful to be aware of. Obviously, programming style is largely a matter of taste; however, a few guidelines generally acknowledged by the Scala community can help someone new to Scala to write easier-to-read and more maintainable code. This section is dedicated to showing some of the most common differences.

Writing an algorithm in Java follows an imperative style, that is, a sequence of statements that change a program state. Scala, focusing primarily on functional programming, adopts a more declarative approach, where everything is an expression rather than a statement. Let's illustrate this in an example.

In Java, you would commonly find the following code snippet:

...
String customerLevel = null;
if(amountBought > 3000) {
    customerLevel = "Gold"; 
} else {
    customerLevel = "Silver";
}
...

The Scala equivalent consists...