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)

OO in Our Chatbot


Now that you know the theoretical basics, let's look at these facilities and how they are used in our program. Let's open Lesson 2/3-project in our IDE and extend our chatbot, which was developed in the previous chapter.

Decoupling Logic and Environment

To do this, we must decouple the environment and logic, and integrate only one in the main method.

Let's open the EffectsProvider class:

Note

For full code, refer to Code Snippets/Lesson 2.scala file.

trait EffectsProvider extends TimeProvider {

 def input: UserInput

 def output: UserOutput

}

object DefaultEffects extends EffectsProvider
{
 override def input: UserInput = ConsoleInput

 override def output: UserOutput = ConsoleOutput

 override def currentTime(): LocalTime = LocalTime.now()

 override def currentDate(): LocalDate = LocalDate.now()
}

Here, we encapsulate all of the effects into our traits, which can have different implementations.

For example, let's look at UserOutput:

For full code, refer to Code...