Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
Search icon CANCEL
Subscription
0
Cart icon
Your Cart(0 item)
Close icon
You have no products in your basket yet
Save more on your purchases!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Programming> Programming Language> Professional Scala
Professional Scala
Professional Scala

Professional Scala: Combine object-oriented and functional programming to build high-performance applications

Arrow left icon
Profile Icon HartmannProfile Icon Shevchenko
Arrow right icon
Can$39.99Can$44.99
Full star iconFull star iconFull star iconFull star iconHalf star icon4.2(13 Ratings)
eBookJul 2018186 pages1st Edition
eBook
Can$39.99 Can$44.99
Paperback
Can$55.99
Subscription
Free Trial
Arrow left icon
Profile Icon HartmannProfile Icon Shevchenko
Arrow right icon
Can$39.99Can$44.99
Full star iconFull star iconFull star iconFull star iconHalf star icon4.2(13 Ratings)
eBookJul 2018186 pages1st Edition
eBook
Can$39.99 Can$44.99
Paperback
Can$55.99
Subscription
Free Trial
eBook
Can$39.99 Can$44.99
Paperback
Can$55.99
Subscription
Free Trial

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview book icon Preview Book

Professional Scala

Chapter 1. Setting up the Development Environment

Before we start writing the various programs in this book, let's talk a little about the Scala language itself. Why is it necessary, and what has made Scala unique? What are the most important aspects of the language?

Scala was created in 2001 in EPFL (École Polytechnique Fédérale de Lausanne), by Martin Odersky. This is the same lab where Pascal language (widely used up to the end of the 1990s) was created.

Scala is an abbreviation for 'Scalable Language'—a language which can be scaled, that is, it allows you to write complex systems with gigantic amounts of functionality. As specified on Scala's home page: "Scala combines object-oriented and functional programming in one concise, high-level language."

Note

You can visit Scala's official home page here:https://www.scala-lang.org/

By the end of this chapter, you will be able to:

  • Recognize the structure of a Scala project
  • Identify the use of Scala's sbt tool (interactive build tool) for building and running your project
  • Identify how to use the IDE
  • Implement interactions with a simple chatbot

Scala is built on top of the JVM platform (the Scala program is compiled to use JVM bytecode).

Now, the language is used as one of the most preferred platforms in many areas, such as high-load soft-realtime applications, ad servers for data science toolkits.

Some characteristics of Scala are as follows:

  • An advanced type system, which makes Scala superior (but at the same time, more complex) compared to most other industrial programming languages.
  • Static typing, which allows you to write code in a safe way when errors are checked during compilation.

In this chapter, we will learn the basics of Scala, such as what the simple Scala program looks like and what a typical developer flow is. A significant part of development is interaction with tools—build tools, dependency extractors, IDEs, and so on, which form the tool ecosystem with the language. We will build a simple program using mainstream tools.

Simple Program

In this section, we will be covering the structure of a basic Scala program. We will be covering definitions such as packages, imports, and objects. We will also be looking into the main method of a Scala program.

Let's create the simplest possible program in Scala. We will implement a program which will print "Hello World" on the screen. The structure of this program is defined as follows:

package com.packt.coursewareimport scala.io.StdInobject Chatbot1{   def main(args: Array[String]):Unit =  {     // do something   }}

Definitions: Packages, Imports, and Objects

If you look at the preceding code, the first line is a package name. In our case, this iscom.packt.courseware.

All compilation units are organized into packages. Packages can be nested, forming hierarchical namespaces for code objects.

When a compilation unit has no package declaration, it belongs to a so-called 'default' package. Modules from a default package can't be imported from another package.

Usually, the source directory in a Scala project is organized in the same way as packages. This is not mandatory, but becomes a rule of thumb. Some tools (such as IDEs) use these conventions for default project settings.

Now we will look atimport statements.

Object Definition

Here, we define the objectChatbot1.

If you are familiar with the traditional classes, since they are implemented in Java, you can look at the object of a class with one default instance, that is, an object is an implementation of the singleton pattern: on the JVM level, the object definition creates a class and one predefined instance of this class.

The main Method

Finally, themain method is an entry point for our program. It must accept an array of strings (command-line arguments) and return a unit.

Historically, themain method name is used in Scala. This is because the Java language is following the same tradition, which takes the name of an entry method from C, which take this from BCPL.

The method is defined as follows:

         package com.packt.couserware    object X  { def f() = { … } }

Inside main

Themain method is an essential part of any Scala program. The execution of a program first starts from themain method.

Let's look inside themain method:

def main(args: Array[String]): Unit = {val name = StdIn.readLine("Hi! What is your name?")println(s" $name, tell me something interesting, say 'bye' to end the talk")var timeToBye = false  while (!timeToBye)timeToBye = StdIn.readLine(">") match {case "bye" => println("ok, bye")                             truecase  _      => println("interesting...")false}}

Here, we define an immutable value with the namename, which keeps the user's input fromstdin. Scala is a statically typed language, and so the value is of typeString.

As we can see, the type of the value is not explicitly written, but automatically inferred from its context.

At the next line, the value is printed using the "string interpolation" operator: In a string with a prefix ofs, all occurrences of expressions inside${} brackets in strings are replaced with values of these expressions, casted to strings. For simple identifiers, we canomit {} brackets, for example, in a string interpolation ofs"x=$y", the value of y will be substituted instead with$y.

var timeToBye is a mutable variable with aBoolean type. Unlike values, mutable variables can be assigned more than once.

Looking forward at the loop, we can see that the program is trying to be a good listener and answerinteresting to any message, exceptbye.

The result of the case statement is assigned totimeToBye, and is checked in thewhile loop condition

Scala, as a multiparadigm language, has both mutable and immutable variables. For nearly any task, we can choose more than one way of implementing this.

If guidelines exist, where should we use mutable variables and where should we use immutable variables?

Generally, reasoning about immutable variables is simpler. The usual heuristic is to use immutable values as much as possible, leaving mutable variables for performance-critical sections and state-check language constructs (such as while loops).

In our small example, we can eliminate the mutable flag by putting an expression for the loop exit condition insidewhile. The resulting code is smaller and better to read, but adding new functionality becomes harder. Yet there is one possibility—use therecursive function instead of the loop language construction.

Now let's add some functionality to ourchatbot: when the user asks for thetime, thechatbot should report the current time.

To do this, we must retrieve the current time using the Java API and display the output of the time using string interpolators.

For example, use thenow method ofjava.time.LocalTime.

The code used to display this will beprintln("time is ${java.time.LocalTime.now()}").

The following is the code for this functionality, but we will actually implement this after setting up the working environment we will be playing with:

package com.packt.coursewarepackage com.packt.coursewareimport scala.io.StdInobject Chatbot1 {  def main(args: Array[String]): Unit = {    val name = StdIn.readLine("Hi! What is your name?")    println(s" $name, tell me something interesting, say 'bye' to end the talk")    var timeToBye = false    while (!timeToBye)       timeToBye = StdIn.readLine(">") match {         case "bye" => println("ok, bye")         true         case "time" => println(s"time is ${java.time.LocalTime.now()}")         true         case _ => println("interesting...")         false       }}}

Structure of a Scala Project

Let's look at ourchatbot program in a complete runnable project. Let's navigate to the/day1-lesson1/1-project directory in our code supplement.

Note

The code is available on Github at the following link:https://github.com/TrainingByPackt/Professional-Scala

The preceding diagram is the typical directory structure of a Scala project. If you are familiar with the Java tools ecosystem, then you will notice the similarities between themaven project layout.

Insrc, we can see project sources (main andtest).target is a place where output artifacts are created, whereasproject is used as a place to internally build the project. We will cover all of these concepts later on.

organization := "com.packt.courseware"name := "chatbot1"version := "0.1-SNAPSHOT"scalaVersion := "2.12.4"

The head of any project is itsbuild.sbt file. It consists of the following code:

The text inside it is a plain Scala snippet.

organization,name, andversion are instances ofsbt.key. For this point of view,:= is a binary operator defined onkeys. In Scala, any method with two arguments can be used with the syntax of a binary operator.:= is a valid method name.

build.sbt is interpreted by thesbt tool.

Note

sbt – The original intention for the name, whensbt was created by Mark Harrah, was 'Simple Build Tool'. Later on, the author decided to avoid such a decipherment, and kept it as it was. You can read about the details ofsbt here:https://www.scala-sbt.org/1.x/docs/index.html.

Basic sbt Commands

We will nowtalk about the basicsbt commands.

sbt compile should compilethe project and live somewhere in its target compiled Java classes.

sbt run executes themain function of the project. Therefore, we can try to interact with ourchatbot:

rssh3:1-project rssh$ sbt run[info] Loading global plugins from /Users/rssh/.sbt/0.13/plugins[info] Set current project to chatbot1 (in build file:/Users/rssh/work/packt/professional-scala/Lesson 1/1-project/)[info] Running com.packt.courseware.Chatbot1Hi! What is your name? Jon  Jon, tell me something interesting, say 'bye' to end the talk
>qqqinteresting..>dddinteresting...>byeok, bye [success] Total time: 19 s, completed Dec 1, 2017 7:18:42 AM

The output of the code is as follows:

sbt package prepares an output artifact. After running it, it will create file calledtarget/chatbot1_2.12-0.1-SNAPSHOT.jar.

chatbot1 is the name of our project;0.1-SNAPSHOT – version. 2.12 is the version of the Scala compiler.

Scalaguarantees binary compatibility only within the scope of a minor version. If, for some reason, the project still usesscala-2.11, then it must use the library, which was created forscala-2.11. On the other hand, updating to the next compiler version can be a long process for projects with many dependencies. To allow the same library to exist in the repository with differentscalaVersions, we need to have an appropriate suffix in the jar file.

sbt publish-local – publishes the artifact on to your local repository.

Now let's seeour sample project andsbt tool.

Activity: Performing Basic Operations with sbt: Build, Run, Package

  1. Install sbt on your computer, if not installed beforehand.
  2. Start thesbt console by typingsbt console in the root directory of the1-project(wherebuild.sbt is situated).
  3. Compile the code by typing thecompile command into thesbt console.
  4. Run the program by typing thesbt run command into thesbt console.
  5. When running this, saybye to the bot and return to the console.
  6. Package the program by typingpackage into thesbt console.

IDE

Another part of thedeveloper toolbox is an IDE tool (Integrated Development Environment). For our book, we will use Intellij IDEA community edition with the Scala plugin. This is not the only option: other alternatives are scala-ide, based on IBM Eclipse and Ensime (http://ensime.github.io/), which brings IDE features to any programmable text editors, from vi to emacs.

All tools support importing the project layout frombuild.sbt.

Activity: Loading and Running a Sample Project in the IDE

  1. Importourproject:
    • Go toFile ->Import -> navigate tobuild.sbt
  2. Open the program in IDE:
    • Start IDEA
    • PressOpen
    • Selectday1-lesson1/1-project/build.sbt
  3. In the dialog window, which asks whether toopen it as a file or as a project, selectproject.
  4. On the left part of the project's structure, unfoldsrc entry.
  5. Click onmain.
  6. Ensure that you can seemain, as specified in the code.
  7. Ensure that project can be compiled and run via thesbt console.

For running our project from the IDE, we should edit the project's configuration (Menu:Build/Edit configuration orRun/Edit configuration, depending on which version of IDEA you are using).

Running the Project from IDE:

  1. SelectRun/Edit Configuration.
  2. SelectApplication.
  3. Set the application's name. In our case, useChatbot1.
  4. Set the name of theMain class. In our case, it must becom.packt.courseware.Chatbot1.
  5. Actually run the application: select Run, then Chatbot1 from the dropdown menu.

REPL

Another toolthat we will frequently use is REPL (Read Eval Print Loop). It is often used for quickly evaluating Scala expressions.

Fromsbt, we can enter REPL mode with the help of thesbt console command. Let's try somesimple expressions.

Now, we'll look at how to evaluate expressions. Follow these steps to do so:

  1. Open thesbt tool.
  2. OpenREPL by typing the following command:
    sbt console
  3. Type the following expressions and pressEnter:
    • 2 + 2
    • "2" + 2
    • 2 + "2"
    • (1 to 8).sum
    • java.time.LocalTime.now()

Please note that we can have an interactive Scalaplayboard inside IDE by creating a special file type: a Scala Worksheet. It's useful, but is mainly for demonstration purposes.

Obtaining the Time Request from Our Chatbot Program

For now, let's return to our task: modifying thechatbot program so that it replies withthe current time, as requested by the use oftime. Let's learn how to do this:

Steps for Completion

  1. Check fortime to match the statement:
    case "time" =>
  2. Retrieve the current time using the Java API. Use thenow method ofjava.time.LocalTime:
         java.time.LocalTime.now()
  3. Display the output of the time using string interpolators, as follows:
    println("time is ${java.time.LocalTime.now()}")

Themain method will look like this:

def main(args: Array[String]): Unit = {val name = StdIn.readLine("Hi! What is your name?")println(s" $name, tell me something interesting, say 'bay' to end the talk")var timeToBye = falsewhile (!timeToBye)timeToBye = StdIn.readLine(">") match {case "bye" => println("ok, bye")truecase "time" => println(s"time is ${java.time.LocalTime.now()}")truecase _ => println("interesting...")false}}

After we prepare and package our artifacts, we need to run them as well.

In this book, we willuse the running system from unpackaged sources viasbt (as in the early days of Ruby applications), assuming that sources andsbt tools are accessible from the production environment. Using this, we can use build tool commands for sources such assbt run. In real life, packaging for production is a bit more complex.

Popular methods for doing this are as follows:

  • Preparing a fat jar (which includes all dependencies). Ansbt plugin for this exists, which can be found at the following link:https://github.com/sbt/sbt-assembly.
  • Preparing a native system package (which includes jars, dependencies, custom layouts, and so on). There is also ansbt plugin to create native system packages, which can be found at the following link:https://github.com/sbt/sbt-native-packager.

Base Syntax

Now that we can use REPL, let's understand the base Scala syntax. For now, it's notnecessary to learn it in detail, but let's get familiar with it by using an example.

Note

For a formal, detailed description, refer to the SLS: Scala Language Specification here:http://scala-lang.org/files/archive/spec/2.12/.

Base Syntax for Definitions

Scalacompilation unit – This is a set of definitions inside an entity (template-entity), which can be an object, a class, or a trait. We will speak about the Object-Oriented part of the Scala language in detail later. Now, let's look at the basic syntax. Let's define some classes in REPL:

> class X {  def f():Int = 1 }> Class X defined  // answer in REPL

Definitions inside the entity can be nested entities, functions, or values:

> def f():Int = 1

Here, the functionf is defined, returning1. We will talk about this function in detail inChapter 3,Functions. Now, let's stay on the top-level view:

> val x = 1

Here, the valuex is defined with value1:

> var y = 2

Here, the mutable variabley is defined with value2.

Other high-level entities include objects and traits. We can create objects by writing object or trait definitions:

>  object O {  def f():Int =1  }>  trait O {  def f():Int =1  }


We will talk about classes, objects, and traits in the next chapter.

Now, let's look at defining an object in REPL with the name ZeroPoint.

Steps for Completion:

  1. Open REPLby typing the following command insbt:
    sbt console
  2. Type in the following commands in REPL:
    >  object ZeroPoint {>     val x:Int = 0>     val y:Int = 0> }

Base Syntax for Expressions

Scala is anexpression-based language, which means that everything is an expression (in the right-hand side of function and value/variable definitions).

Some of the base expressions are:

  • Primitive expression: Constant or value/variable name.
  • Function calls: These can be:
    • Usual function callsf(x, y).
    • Operator call syntax:
    • binary:x + y.

    Note

    Any method with an argument can be used as a binary operator. A set of predefined binary operators are similar to Java:

  • unary:!x
  • Constructors:new x creates an instance of class x.
  • Assignments to mutable variables:
    • y = 3: Assigns a value of3 toy.
    • x = 3: This is a compiler error, and a value can't be assigned.
  • Block:
    { A; B }

    The valueof a block expression is the last expression. Note that; can be omitted ifA andB are situated on different lines. The syntax for this is shown as follows:

    {   A   B}

The preceding syntax will have the same output as{ A; B }.

  • Control structures
    • if statement:
             >  if (1 == 1)  "A"  else "B"       - let's eval one in REPL
    • match/case expressions:
          >  x match {         case "Jon"  =>  doSomethingSpecialForJon()         case "Joe" =>   doSomethingSpecialForJoe()         case   _   => doForAll()      }
    • Loops:
    • while/do
           var i=0      var s=0      while(i < 10) {          s = s+i          i = i +1      }
    • Do/while
    • Foreach,for

Shortcuts for height-order functions will be described in detail in,Chapter 4,Scala Collections.

We'll look at defining a main function which prints something onscreen and calls the main function.

  1. You should have already openedproject1. If you haven't, import it into the IDE.
  2. Insert the new method inside the object definition.
  3. Insert call at themain method.

The full method should look something like this:

  object Chatbot1 {def printHello():Unit = {println("Hello")}def main(args: Array[String]): Unit = {printHello() … // unchanged code here     }}

Unit Testing

In any programwhich is bigger than arithmetic operations, programmers should make themselves comfortable when it is possible to ensure that new changes are not breaking old functionalities.

The mostcommon technique for this is unit testing, which is where the programmer tests the functionality of the code in parallel with its development by creating a test code which will verify that the code really satisfies their requirements.

The theme of this section will be introducing tools for unit testing in Scala.

Adding a Test to Our Project

Let's add teststo our small program. We'll import<for-students/lesson1/2-project> in our IDE.

This is the directory schema of a Scala project. For adding tests, we should do the following:

  • Add test dependencies tobuild.sbt
  • Write tests in the source test directory

For adding dependency, let's add the following line to ourbuild.sbt:

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.4" % "test"

It's anexpression in Scala DSL (domain-specific language), which means that we should addscalatest to our set of librarydependencies. Operators%% and% are used for forming the name and classifier for published artifacts. You can refer to thesbt documentation for more detail:http://www.scala-sbt.org/1.x/docs/Library-Dependencies.html.

Before compilation,sbt will downloadscalatest from a publicly available repository (Maven central), and when running tests, it will addscalatest to the classpath.

We willnow runsbt tests from the command line.

  1. In the command-line environment, navigate to the root of the project and select the following test:
      Lesson 1/2-project
  2. If you are using a Unix/Linux machine and your code is situated incourses/pactscala of your homedirectory, then run the following command:
     > cd  ~/courses/packscala/Lesson 1/2-project
  3. Run the following command:
        > sbt test
  4. You willget the expected output, which will include the following strings:
    [info] ExampleSpec:[info] - example test should pass[info] StepTest:[info] - step of unparded word must be interesting

We will now see how to runsbt tests from IDEA IDE.

We'll now run sbt Tests from IDEA IDE.

  1. Open the project in the IDE.
  2. Navigate toRun/Edit Configurations:
    Adding a Test to Our Project
  3. Choose sbt test as the configuration.
    • Check the checkboxUse sbt:
    Adding a Test to Our Project
  4. SelectRun sbt-test.

Inside Tests

Now let's look ata simple test:

package com.packt.courseware.l1import org.scalatest.FunSuiteclass ExampleSpec extends FunSuite {  test("example test  should pass") {     assert(1==1)  }}

Here, we definea class which is inherited from scalatest FunSuite.

The test expression is called. When theFunSuite class is initialized and added to a set of tests, the test withname example test should pass and assert an expression as an argument. For now, this looks like magic, but we will show you how to build such DSLs in the next chapter.

Let's run our test with the help ofsbt:

sbt test

This command will run all tests and evaluate the test expression.

Now, we'll add another test.

  1. Add one more test to the same file:src/test/scala/com/packt/courseware/l1/ExampleSpec.scala in 2-project
  2. We write onetrivial test, which asserts thefalse expression:
          test("trivial")  {            assert(false)       }
  3. Run the test and look at error reporting.
  4. Invert theexpression in assert so that the test passes:
          test("trivial")  {            assert(true)       }
  5. Run thesbt test again to ensure that all of the tests pass.

Running Tests for Chatbot

Remember that,when writingchatbot, we want to test one functionality. Our original program only has one function (main), which contains all of the logic and can't be split into testable parts.

Let's look at Version 2.

Note

Please importLesson 1/2-project into your IDE.

package com.packt.courseware.l1import java.time.LocalTimeimport java.time.format.DateTimeFormatterimport scala.io.StdIncase class LineProcessResult(answer:String,timeToBye:Boolean)object Chatbot2 {  def main(args: Array[String]): Unit = {    val name = StdIn.readLine("Hi! What is your name? ")    println(s" $name, tell me something interesting, say 'bye' to end the talk")    var c = LineProcessResult("",false)    while(!c.timeToBye){      c = step(StdIn.readLine(">"))      println(c.answer)    }  }  def step(input:String): LineProcessResult = {    input match {      case "bye" => LineProcessResult("ok, bye", true)      case "time" => LineProcessResult(LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),false)      case _ => LineProcessResult("interesting...", false)    }  }}

Here, we see some new constructs:

LineProcessingResult is a case class, where the result of processing one of the lines (that is, thechatbot answer and quit flag) is stored.

What is the wordcase before class?

case classes canparticipate in pattern matching (while we call onecase) and are usually used for data objects. We will look atcase classes during the next chapter. It is important to see that an instance ofcase classes can be created with theLineProcessingResult(x,y) syntax (that is, withoutnew) and an argument to case class constructors (answers andtimeToBye), which automatically become instance variables of thecase class.

The functionality of processing one line is encapsulated in thestep method, which we can test.

Step receives input from the method argument, not fromSystem.in, therefore making it easier to test. In the case of directly testing themain method, we will need to substituteSystem.in beforetest and return one back after the test is finished.

Ok, let's focus on the first test:

package com.packt.courseware.l1import org.scalatest.FunSuiteclass StepTestSpec extends FunSuite {  test("step of unparded word must be interesting") {    val r = Chatbot2.step("qqqq")    assert(! r.timeToBye)    assert(r.answer == "interesting...")  }}

Writing thesecond test in the same manner will be an easy task. We will look at this in the following exercise.

Now, let's add the second test, which checks bye.

  1. Add a second test to theStepTestSpec class in our project:
    test("after bye, timeToBye should be set to true"){}
  2. In this test:
    • Call the step function withbye as a parameter:
      val r = Chatbot2.step("bye")
    • Check that after this call thattimeToQuit in the returned class is set totrue:
      assert(! r.timeToBye)
  3. The whole code should be as follows:
    test("after bye, timeToBye should be set to true") {  val r = Chatbot2.step("bye")assert(! r.timeToBye)
  4. Runsbt test.

A morecomplex task would be to write a test for the time query.

Please note that we can't run the test with the concrete time value, but at least we can be sure that the bot answer can't be parsed back to the time form.

So, what can we do to check the line answer and try to transform it back to time? The solution is provided in the following code:

test("local time must be parser") {val r = Chatbot2.step("time")val formatter = DateTimeFormatter.ofPattern("HH:mm:ss")val t = LocalTime.parse(r.answer,formatter)// assertion is not necessary}

Note that assertion is not necessary. If time does not satisfy the given format, then an exception will be thrown.

It is a good practice to separate functional and effects time for testing. To do this, we will need to substitute the provider of the system time via own.

This will be the first practical task in the next chapter.

Now, let's add the date command to our chatbot program.

  1. Add the following code to the match statement so that it checks for thedate command, which should output the local date inDD:MM:YYYY format:
      case "date" => LineProcessResult(LocalDate.now().format(DateTimeFormatter.ofPattern("dd:YYYY-MM")),false)
  2. Add a test case for this function.
  3. The resulting code will be as follows:
    test("local date must be parser") {val r = Chatbot2.step("date")val formatter = DateTimeFormatter.ofPattern("dd:MM-YYYY")val t = LocalDate.parse(r.answer,formatter)// assertion is not necessary}

Summary

We have reached the end of the chapter. In this chapter, we learned various aspects of setting up the development environment. We covered the structure of a Scala project, and we identified the use ofsbt for building and running projects. We covered REPL, which is a command-line interface for running Scala code. We also covered how to develop and run code over the IDEA IDE. Finally, we implemented interactions with our simplechatbot application.

In the next chapter, we will cover the structure of a Scala program and dive deep into the object-oriented properties in Scala, such as like classes, objects, and traits. We will also cover the syntax for calling functions and various parameter-passing models.

Left arrow icon

Page1 of 6

Right arrow icon

Key benefits

  • Expert guidance that shows you to efficiently use both object-oriented and functional programming techniques
  • Understand functional programming libraries, such as Cats and Scalaz, and use them to augment your Scala development
  • Perfectly balances theory and hands-on exercises, assessments, and activities

Description

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.

Who is this book for?

This is an ideal book for developers who are looking to learn Scala, and is particularly well suited for Java developers looking to migrate across to Scala for application development on the JVM.

What you will learn

  • Understand the key language syntax and core concepts for application development
  • Master the type system to create scalable type-safe applications while cutting down your time spent debugging
  • Understand how you can work with advanced data structures via built-in features such as the Collections library
  • Use classes, objects, and traits to transform a trivial chatbot program into a useful assistant
  • Understand what are pure functions, immutability, and higher-order functions
  • Recognize and implement popular functional programming design patterns

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date :Jul 31, 2018
Length:186 pages
Edition :1st
Language :English
ISBN-13 :9781789534702
Category :
Languages :

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

Publication date :Jul 31, 2018
Length:186 pages
Edition :1st
Language :English
ISBN-13 :9781789534702
Category :
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99billed monthly
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconSimple pricing, no contract
$199.99billed annually
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick iconExclusive print discounts
$279.99billed in 18 months
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick iconExclusive print discounts

Frequently bought together


Modern Scala Projects
Modern Scala Projects
Read more
Jul 2018334 pages
eBook
eBook
Can$49.99Can$55.99
Can$69.99
Professional Scala
Professional Scala
Read more
Jul 2018186 pages
Full star icon4.2 (13)
eBook
eBook
Can$39.99Can$44.99
Can$55.99
Scala Programming Projects
Scala Programming Projects
Read more
Sep 2018398 pages
Full star icon3.8 (5)
eBook
eBook
Can$49.99Can$55.99
Can$69.99
Stars icon
TotalCan$195.97
Modern Scala Projects
Can$69.99
Professional Scala
Can$55.99
Scala Programming Projects
Can$69.99
TotalCan$195.97Stars icon

Table of Contents

9 Chapters
1. Setting up the Development EnvironmentChevron down iconChevron up icon
1. Setting up the Development Environment
Simple Program
Structure of a Scala Project
Base Syntax
Unit Testing
Summary
2. Basic Language FeaturesChevron down iconChevron up icon
2. Basic Language Features
Objects, Classes, and Traits
OO in Our Chatbot
Function Calls
Summary
3. FunctionsChevron down iconChevron up icon
3. Functions
Functions
Exploring Pattern Matching
Partial Functions in Practice
Summary
4. Scala CollectionsChevron down iconChevron up icon
4. Scala Collections
Working with Lists
Abstracting on Sequences
Other Collections
Summary
5. Scala Type SystemChevron down iconChevron up icon
5. Scala Type System
Type Basics and Polymorphism
Variance
Advanced Types
Summary
6. ImplicitsChevron down iconChevron up icon
6. Implicits
Implicit Parameters and Implicit Conversions
Ad Hoc Polymorphism and Type Classes
Summary
7. Functional IdiomsChevron down iconChevron up icon
7. Functional Idioms
Introduction to Functional Programming Concepts
Functional Design Patterns
Popular Libraries
Summary
8. Domain Specific LanguagesChevron down iconChevron up icon
8. Domain Specific Languages
DSLs and Types of DSLs
ScalaTest – A Popular DSL
Language Features for Writing DSLs
Writing a Small DSL
Beyond This Book
Summary
IndexChevron down iconChevron up icon
Index

Recommendations for you

Left arrow icon
Debunking C++ Myths
Debunking C++ Myths
Read more
Dec 2024226 pages
Full star icon5 (1)
eBook
eBook
Can$35.99Can$40.99
Can$50.99
Go Recipes for Developers
Go Recipes for Developers
Read more
Dec 2024350 pages
eBook
eBook
Can$35.99Can$40.99
Can$50.99
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
Can$44.99Can$50.99
Can$63.99
Can$63.99
Asynchronous Programming with C++
Asynchronous Programming with C++
Read more
Nov 2024424 pages
Full star icon5 (1)
eBook
eBook
Can$37.99Can$42.99
Can$53.99
Modern CMake for C++
Modern CMake for C++
Read more
May 2024504 pages
Full star icon4.7 (12)
eBook
eBook
Can$44.99Can$50.99
Can$63.99
Learn Python Programming
Learn Python Programming
Read more
Nov 2024616 pages
Full star icon5 (1)
eBook
eBook
Can$35.99Can$40.99
Can$50.99
Learn to Code with Rust
Learn to Code with Rust
Read more
Nov 202457hrs 40mins
Video
Video
Can$94.99
Modern Python Cookbook
Modern Python Cookbook
Read more
Jul 2024818 pages
Full star icon4.9 (21)
eBook
eBook
Can$49.99Can$55.99
Can$69.99
Right arrow icon

Customer reviews

Top Reviews
Rating distribution
Full star iconFull star iconFull star iconFull star iconHalf star icon4.2
(13 Ratings)
5 star53.8%
4 star23.1%
3 star15.4%
2 star0%
1 star7.7%
Filter icon Filter
Top Reviews

Filter reviews by




Sviatoslav KsondzykMay 01, 2020
Full star iconFull star iconFull star iconFull star iconFull star icon5
Udemy Verified reviewUdemy
Alex KalinichevNov 26, 2022
Full star iconFull star iconFull star iconFull star iconFull star icon5
Udemy Verified reviewUdemy
Parthasarathy ChakravarthyNov 17, 2021
Full star iconFull star iconFull star iconFull star iconFull star icon5
Udemy Verified reviewUdemy
Mikhail KaluginFeb 06, 2021
Full star iconFull star iconFull star iconFull star iconFull star icon5
Udemy Verified reviewUdemy
Paritosh sharmaDec 10, 2019
Full star iconFull star iconFull star iconFull star iconFull star icon5
Udemy Verified reviewUdemy
  • Arrow left icon Previous
  • 1
  • 2
  • 3
  • Arrow right icon Next

People who bought this also bought

Left arrow icon
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
Can$44.99Can$50.99
Can$63.99
Can$63.99
Event-Driven Architecture in Golang
Event-Driven Architecture in Golang
Read more
Nov 2022384 pages
Full star icon4.9 (11)
eBook
eBook
Can$44.99Can$50.99
Can$63.99
The Python Workshop Second Edition
The Python Workshop Second Edition
Read more
Nov 2022600 pages
Full star icon4.6 (22)
eBook
eBook
Can$46.99Can$52.99
Can$65.99
Template Metaprogramming with C++
Template Metaprogramming with C++
Read more
Aug 2022480 pages
Full star icon4.6 (14)
eBook
eBook
Can$42.99Can$47.99
Can$59.99
Domain-Driven Design with Golang
Domain-Driven Design with Golang
Read more
Dec 2022204 pages
Full star icon4.4 (19)
eBook
eBook
Can$40.99Can$45.99
Can$56.99
Right arrow icon

About the authors

Left arrow icon
Profile icon Hartmann
Hartmann
Mads Hartmann is a software engineer with a fondness for automation and programming languages, especially statically typed functional ones. He holds a masters degree in computer science from the University of Copenhagen and he is currently working as a full-stack engineer at Family. He is active in the Copenhagen developer scene and has organized a meetup group for people interested in Scala.
Read more
See other products by Hartmann
Profile icon Shevchenko
Shevchenko
Ruslan Shevchenko is a system architect and a software developer who is focused on building reliable software systems. During his career patch, he was involved in projects using many languages, from Scala, Java to C++, C, Perl, and Tcl in numerous areas, such as telecommunications, OSS/billing systems, finance, code analysis, social integration, system utilities. In terms of architecture, his specialist domains are large-scale software systems and distributed processing.
Read more
See other products by Shevchenko
Right arrow icon
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook?Chevron down iconChevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website?Chevron down iconChevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook?Chevron down iconChevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support?Chevron down iconChevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks?Chevron down iconChevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook?Chevron down iconChevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.


[8]ページ先頭

©2009-2025 Movatter.jp