Book Image

Learning Scala Programming

By : Vikash Sharma
Book Image

Learning Scala Programming

By: Vikash Sharma

Overview of this book

Scala is a general-purpose programming language that supports both functional and object-oriented programming paradigms. Due to its concise design and versatility, Scala's applications have been extended to a wide variety of fields such as data science and cluster computing. You will learn to write highly scalable, concurrent, and testable programs to meet everyday software requirements. We will begin by understanding the language basics, syntax, core data types, literals, variables, and more. From here you will be introduced to data structures with Scala and you will learn to work with higher-order functions. Scala's powerful collections framework will help you get the best out of immutable data structures and utilize them effectively. You will then be introduced to concepts such as pattern matching, case classes, and functional programming features. From here, you will learn to work with Scala's object-oriented features. Going forward, you will learn about asynchronous and reactive programming with Scala, where you will be introduced to the Akka framework. Finally, you will learn the interoperability of Scala and Java. After reading this book, you'll be well versed with this language and its features, and you will be able to write scalable, concurrent, and reactive programs in Scala.
Table of Contents (21 chapters)
Title Page
Packt Upsell
Contributors
Preface
Index

Partial functions


Partial functions do not suffice for every input given, which means these are defined to serve a purpose for a specific set of input parameters. To understand more, let's first define a partial function:

scala> val oneToFirst: PartialFunction[Int, String] = { 
     | case 1 => "First" 
     | } 
oneToFirst: PartialFunction[Int, String] = <function1> 
 
scala> println(oneToFirst(1)) 
First 

In the preceding code, we defined a partial function named oneToFirst. We also specified type parameters for our partial function; in our case we passed IntString. The PartialFunction function is a trait in Scala, defined as:

trait PartialFunction[-A, +B] extends (A) => B 

The trait as shown expects two parameters A and B, that become the input and output types of our partial function. Our oneToFirst partial function simply expects 1 and returns a string representation for 1 as first. That's why when we try to call the function by passing 1, it works fine; but if we try...