Book Image

Professional Scala

By : Mads Hartmann, Ruslan Shevchenko
Book Image

Professional Scala

By: Mads Hartmann, Ruslan Shevchenko

Overview of this book

This book teaches you how to build and contribute to Scala programs, recognizing common patterns and techniques used with the language. You’ll learn how to write concise, functional code with Scala. After an introduction to core concepts, syntax, and writing example applications with scalac, you’ll learn about the Scala Collections API and how the language handles type safety via static types out-of-the-box. You’ll then learn about advanced functional programming patterns, and how you can write your own Domain Specific Languages (DSLs). By the end of the book, you’ll be equipped with the skills you need to successfully build smart, efficient applications in Scala that can be compiled to the JVM.
Table of Contents (12 chapters)

Function Calls


Now, we'll look at how function calls are implemented in Scala.

Syntax Goodies

Scala provides flexible syntax and it is worth dedicating a few minutes to this concept.

Named Parameters

The following is a function, f(a:Int, b:Int). We can call this function using the named parameter syntax: f(a = 5, b=10). If we swap the parameters but leave the correct names, the method will still be correct.

It is possible to combine positional and named function calls—the first few arguments can be positional.

For example:

def f(x:Int, y:Int) = x*2 + y
f(x=1,y=2) // 4
f(y=1,x=2) // 5

Default Parameters

When specifying a function, we can set default parameters. Then, later, when we call this function, we can omit parameters and the compiler will substitute defaults:

def f(x:Int, y:Int=2) = x*2 + y
f(1) // 4

It is possible to create a comfortable API with the help of the combination of named and default arguments. For example, for case classes with N components, the compiler generates a copy...