Scala Programming Projects
eBook - ePub

Scala Programming Projects

Build real world projects using popular Scala frameworks like Play, Akka, and Spark

  1. 398 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Scala Programming Projects

Build real world projects using popular Scala frameworks like Play, Akka, and Spark

About this book

Discover unique features and powerful capabilities of Scala Programming as you build projects in a wide range of domains

Key Features

  • Develop a range of Scala projects from web applications to big data analysis
  • Leverage full power of modern web programming using Play Framework
  • Build real-time data pipelines in Scala with a Bitcoin transaction analysis app

Book Description

Scala is a type-safe JVM language that incorporates object-oriented and functional programming (OOP and FP) aspects. This book gets you started with essentials of software development by guiding you through various aspects of Scala programming, helping you bridge the gap between learning and implementing. You will learn about the unique features of Scala through diverse applications and experience simple yet powerful approaches for software development.

Scala Programming Projects will help you build a number of applications, beginning with simple projects, such as a financial independence calculator, and advancing to other projects, such as a shopping application and a Bitcoin transaction analyzer. You will be able to use various Scala features, such as its OOP and FP capabilities, and learn how to write concise, reactive, and concurrent applications in a type-safe manner. You will also learn how to use top-notch libraries such as Akka and Play and integrate Scala apps with Kafka, Spark, and Zeppelin, along with deploying applications on a cloud platform.

By the end of the book, you will not only know the ins and outs of Scala, but you will also be able to apply it to solve a variety of real-world problems

What you will learn

  • Build, test, and package code using Scala Build Tool
  • Decompose code into functions, classes, and packages for maintainability
  • Implement the functional programming capabilities of Scala
  • Develop a simple CRUD REST API using the Play framework
  • Access a relational database using Slick
  • Develop a dynamic web UI using Scala.js
  • Source streaming data using Spark Streaming and write a Kafka producer
  • Use Spark and Zeppelin to analyze data

Who this book is for

If you are an amateur programmer who wishes to learn how to use Scala, this book is for you. Knowledge of Java will be beneficial, but not necessary, to understand the concepts covered in this book.

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Yes, you can access Scala Programming Projects by Mikael Valot, Nicolas Jorand in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in Java. We have over one million books available in our catalogue for you to explore.

Information

Handling Errors

In this chapter, we will continue working on the retirement calculator that we implemented in Chapter 2, Developing a Retirement Calculator. Our calculator worked correctly as long as we passed the right arguments, but would fail badly with a horrible stack trace if any of the parameters were wrong. Our program only worked for what we call the happy path.
The reality of writing production software is that all kinds of error scenarios can occur. Some of them are recoverable, some of them must be presented to the user in an attractive way, and, for some hardware-related errors, we might need to let the program crash.
In this chapter, we will introduce exception handling, explain what referential transparency is, and try to convince you that exceptions are not the best way to deal with errors. Then, we will explain how to use functional programming constructs to effectively handle the possibility of an error.
In each section, we will briefly introduce a new concept, and then use it in a Scala worksheet to get a sense of how to use it. After that, we will apply this new knowledge to improve the retirement calculator.
In this chapter, we will look at the following topics:
  • Using exceptions when necessary
  • Understanding referential transparency
  • Using Option to represent optional values
  • Using Either to handle errors sequentially
  • Using Validated to handle errors in parallel

Setup

If you have not completed Chapter 2, Developing a Retirement Calculator, then you can check out the retirement calculator project at GitHub. If you are not already familiar with Git, I would advise that you read the documents at https://guides.github.com/introduction/git-handbook/ first.
To begin the setup, go through the following steps:
  1. Create an account at https://github.com/ if you do not have one already.
  2. Go to the retirement calculator project at https://github.com/PacktPublishing/Scala-Programming-Projects. Click on Fork in the top-right corner to fork the project into your account.
  3. Once the project is forked, click on Clone or download, and copy the URL into the clipboard.
  4. In IntelliJ, go to File | New | Project from Version Control | GitHub and make the following edits:
    • Git repository URL: Paste the URL of your forked repository
    • Parent directory: Choose a location
    • Directory name: Keep retirement_calculator
    • Click on Clone
  5. The project should be imported in IntelliJ. Click on git: master in the bottom-right of the screen and select Remote branches | origin/chapter2 | Checkout as new local branch. Name the new branch chapter3_yourusername to distinguish it from the final solution, which is in the origin/chapter3 branch.
  6. Build the project with Ctrl + F9. Everything should compile.

Using exceptions

Exceptions are one of the mechanisms that we can use in Scala to handle error scenarios. It consists of two statements:
  • The throw exceptionObject statement stops the current function and passes the exception up to the caller.
  • The try { myFunc() } catch { case pattern1 => recoverExpr1 } statement catches any exception thrown by myFunc() if the exception matches one of the patterns inside the catch block:
  • If an exception is thrown by myFunc, but no pattern matches the exception, the function stops, and the exception is passed up to the caller again. If there is no try...catch block in the call chain that can catch the exception, the whole program stops.
  • If an exception is thrown by myFunc, and the pattern1 pattern matches the exception, the try...catch block will return the recoverExpr1 expression at the right of the arrow.
  • If no exception is thrown, the try...catch block returns the result returned by myFunc().
This mechanism comes from Java, and since the Scala SDK sits on top of the Java SDK, many function calls to the SDK can throw exceptions. If you are familiar with Java, the Scala exception mechanism differs slightly. Exceptions in Scala are always unchecked, which means that the compiler will never force you to catch an exception or declare that a function can throw an exception.

Throwing exceptions

The following is a code snippet that demonstrates how exceptions can be thrown. You can paste it in the Scala console or in a Scala worksheet:
case class Person(name: String, age: Int)
case class AgeNegativeException(message: String) extends Exception(message)

def createPerson(description: String): Person = {
val split = description.split(" ")
val age = split(1).toInt
if (age < 0)
throw AgeNegativeException(s"age: $age should be > 0")
else
Person(split(0), age)
The createPerson function creates the Person object if the string passed in an argument is correct, but throws different types of exceptions if it is not. In the preceding code, we also implemented our own AgeNegativeException isntance, which is thrown if the age passed in the string is negative, as shown in the following code:
scala> createPerson("John 25")
res0: Person = Person(John,25)

scala> createPerson("John25")
java.lang.ArrayIndexOutOfBoundsException: 1
at .createPerson(<console>:17)
... 24 elided

scala> createPerson("John -25")
AgeNegativeException: age: -25 should be > 0
at .createPerson(<console>:19)
... 24 elided

scala> createPerson("John 25.3")
java.lang.NumberFormatException: For input string: "25.3"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at scala.collection.immutable.StringLike.toInt(StringLike.scala:301)
at scala.collection.i...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Packt Upsell
  4. Contributors
  5. Preface
  6. Writing Your First Program
  7. Developing a Retirement Calculator
  8. Handling Errors
  9. Advanced Features
  10. Type Classes
  11. Online Shopping - Persistence
  12. Online Shopping - REST API
  13. Online Shopping - User Interface
  14. Interactive Browser
  15. Fetching and Persisting Bitcoin Market Data
  16. Batch and Streaming Analytics
  17. Other Books You May Enjoy