Professional Scala - Mads Hartmann - E-Book

Professional Scala E-Book

Mads Hartmann

0,0
36,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

If your application source code is overly verbose, it can be a nightmare to maintain. Write concise and expressive, type-safe code in an environment that lets you build for the JVM, browser, and more.




Key Features



  • 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



Book 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.





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





Who this book is 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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 199

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Professional Scala
Why Subscribe?
PacktPub.com
Contributors
About the Authors
Preface
Who This Book Is For
What This Book Covers
What You Need for This Book
Conventions
Installation and Setup
Installing IntelliJ IDE
Installing Scala plugin (make heading)
Reader Feedback
Customer Support
Downloading the Example Code
Errata
Piracy
Questions
1. Setting up the Development Environment
Simple Program
Definitions: Packages, Imports, and Objects
Object Definition
The main Method
Inside main
Structure of a Scala Project
Basic sbt Commands
Activity: Performing Basic Operations with sbt: Build, Run, Package
IDE
Activity: Loading and Running a Sample Project in the IDE
REPL
Obtaining the Time Request from Our Chatbot Program
Base Syntax
Base Syntax for Definitions
Base Syntax for Expressions
Unit Testing
Adding a Test to Our Project
Inside Tests
Running Tests for Chatbot
Summary
2. Basic Language Features
Objects, Classes, and Traits
Object
Classes
Equality and Case Classes
Pattern Matching
Traits
Self-Types
Special Classes
OO in Our Chatbot
Decoupling Logic and Environment
Sealed Traits and Algebraic Datatypes
Function Calls
Syntax Goodies
Named Parameters
Default Parameters
Currying Forms (Multiple Argument Lists)
Special Magic Methods
Implementing + in CartesianPoint
Parameter-Passing Mode
By Value
By Name
By Need
Creating a Runnable Construction
Printing the log Argument to the Console and File
Summary
3. Functions
Functions
Function Values
Function from an OO Point of View
Conversions
Defining and Measuring the Time of a Unit Function
Syntax Sugar in a Function Definition
Partial Functions
Exploring Pattern Matching
Binding a Sequence of Variables in the Pattern Matcher
Partial Functions in Practice
Representing ChatbotMode as a Partial Function
Implementing RemindStore as a Set of Partial Functions
Using Lifting for Conversations between Total and Partial Functions
Summary
4. Scala Collections
Working with Lists
Constructing Lists
Operations on Lists
Pattern Matching on Lists
First-Order Methods on List
Appending and Concatenation
Taking the Length of a List
Reversing a List
Prefixes and Suffixes
Element Selection
Display
Activity: Creating a New Mode for Chatbot Using Lists
Abstracting on Sequences
The Traversable Trait
Iterators
Streams
Activity: Implementing Fibonacci Series Using Streams and Iterators
Other Collections
Sets
Tuples
Maps
Mutable and Immutable Collections
Activity: Implementing the Tower of Hanoi Problem
Summary
5. Scala Type System
Type Basics and Polymorphism
A Unified Type System
Parametric Polymorphism
Type Inference
Parameterized Types
Bounds
Existential Types
Activity: Generalizing the Implementation of the Binary Tree
Variance
Covariance
Contravariance
Invariance
Activity: Implementing Covariance and the Database for Tools
Advanced Types
Abstract Type Members
Structural Types
Option
Higher Kind Types
Type Erasure
Activity: Finding an Element Based on a Given Predicate
Summary
6. Implicits
Implicit Parameters and Implicit Conversions
Implicit Parameters
Implicit Conversions
Implicit Resolution
Activity: Creation of Extension Methods
Ad Hoc Polymorphism and Type Classes
Types of Polymorphism
Type Classes
Context Bounds and Implicitly
Type Classes in the Standard Library
Activity: Implementing Type Classes to Support Conversion
Summary
7. Functional Idioms
Introduction to Functional Programming Concepts
Pure Functions
Immutability
Implementing the standard library
Higher-Order Functions
Functional Design Patterns
Monoids
Using Monoids to Write Polymorphic Functions
Functor
Monads
Popular Libraries
Validating Data Using Cats
Prerequisites for Using Cats
Introduction to Cats
Validating Data
Validating Using Validated
Communicating with Databases Using Doobie
Prerequisites for Doobie
Doobie
ConnectionIO
Transactor
Selecting Rows
Querying Using Parameters
Deleting, Inserting, and Updating Rows
A Complete Example
Activity: Adding Priority to the Todo List
Summary
8. Domain Specific Languages
DSLs and Types of DSLs
External DSLs
Internal DSLs
ScalaTest – A Popular DSL
Adding ScalaTest to Your Project
Overview of ScalaTest Styles
Activity: Implementing ScalaTest Styles
Language Features for Writing DSLs
Flexible Syntax for Method Invocation
By-Name Parameters
Extension Methods and Value Classes
Writing a Small DSL
Modeling Test Cases
DSL for TestCase
Activity: Creating a DSL to Specify Assertions
Beyond This Book
Various Scala Libraries
Akka
Apache Spark
Shapeless
Uncovered Language Features
Macros
Def Macros
Implicit Macros
Quasiquotes
Reflection
Resources to Keep You Updated
Scala Improvement Process
Scala Times
Summary
Index

Professional Scala

Professional Scala

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Acquisitions Editor: Aditya Date

Development Editor: Murtaza Haamid

Production Coordinator: Vishal Pawar

First published: July 2018

Production reference: 1300718

Published by Packt Publishing Ltd.

Livery Place, 35 Livery Street

Birmingham B3 2PB, UK.

ISBN: 978-1-78953-383-5

www.packtpub.com

https://mapt.packtpub.com/

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit https://mapt.packtpub.com/ website.

Why Subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionalsImprove your learning with Skill Plans built especially for youGet a free eBook or video every monthMapt is fully searchableCopy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the Authors

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 he has organized a meetup group for people interested in Scala and co-organized a meetup group for people generally interested in programming languages.

Ruslan Shevchenko is a system architect and a software developer who is focused on building reliable software systems. He specializes in programming languages and frameworks such as Scala, Java (J2SE, J2EE, Android), O/R Mapping, C++ , C, JavaScript, Perl, Tcl, and TermWare.

The domains he specializes in are telecommunications, OSS/billing systems, finance, code analysis, social integration, system utilities architecture domains, large-scale software systems, and distributed processing.

In terms of architecture, his specialist domains are large-scale software systems and distributed processing.

Preface

Scala is a type-safe JVM language that incorporates both object-oriented and functional programming into an extremely concise, logical, and extraordinarily powerful language. Some may be surprised to know that Scala is not quite as new as they may have thought, having first been introduced in 2003. However, it is in the past few years in particular that Scala has begun to develop a significant following.

This book enables you to build and contribute to Scala programs, recognizing common patterns and techniques used with the language.

This is a practical book which provides you with a lot of hands-on experience with Scala.

Who This Book Is For

This book is for developers who are interested in learning about the advanced features of the Scala language. Basic knowledge of the Scala programming language is required to follow the instructions in this book.

What This Book Covers

Chapter 1, Setting up the Development Environment, shows you how to set up your development environment. You'll learn the basics of Scala, such as what the simple Scala program looks like and what a typical developer flow is. It'll also cover some aspects of testing your Scala program by using unit testing.

Chapter 2, Basic Language Features, covers classes and objects, traits, pattern matching, case class, and so on. You'll also implement your chatbot application by applying the object oriented concepts.

Chapter 3, Functions, covers functional programming with Scala and how object- oriented and functional approaches complete each other. You'll identify generic classes and also identify how to create user-defined pattern matching and why is it useful.

Chapter 4, Scala Collections, teaches you how to work with lists. Then, it covers some more relevant data structures. Finally, you'll look at how collections relate to monads and how you can use that knowledge to make some powerful abstractions in your code.

Chapter 5, Scala Type System, covers the type system and polymorphism. It'll also enable you to identify the different types of variance, which provides a way to constrain parameterized types. Then, you'll cover some advanced types such as abstract type members and option.

Chapter 6, Implicits, covers implicit parameters and implicit conversions. You'll be learning about how they work, how to use them, and what kind of benefits and perils they provide.

Chapter 7, Functional Idioms, covers the core concepts of functional programming like Pure functions, immutability, and higher-order functions. It'll also cover two popular functional programming libraries called Cats and Doobie, and use them to write some interesting programs.

Chapter 8, Domain Specifc Languages, covers how Scala makes it possible to write powerful DSLs by providing a few interesting language features. Then, it'll cover a DSL that you'll very likely be using if you're going to work with Scala professionally.

Finally, you'll implement your own DSL.

What You Need for This Book

The minimum hardware requirements are as follows:

Intel Core i3 processor2 GB RAMAn Internet connection

Please ensure you have the following software installed on your machine:

Microsoft Windows 10/8/7 (64 bit)JDK 8IntelliJ + Scala plugin

Mac

macOS 10.5 or higher (64-bit)JDK 8IntelliJ + Scala plugin

Linux

Linux 64-bitKDE, GNOME, or Unity DE desktopJDK 8IntelliJ + Scala plugin

Installation and Setup

Before we start this book, we'll install IntelliJ IDE.

Installing IntelliJ IDE

Visit https://www.jetbrains.com/idea/ in your browser.Click on the DOWNLOAD button on the web page.Choose your appropriate OS and, under Community, click on the Download option.Follow the steps in the installer and that's it! Your IntelliJ IDE is ready.

Installing Scala plugin (make heading)

Open IntelliJ IDEA.Go to File Menu.In the file menu, select Plugins.Click on Browserepositories button and enter Scala.Select Scala plugin to install it.

Reader Feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer Support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the Example Code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Structure of a Scala Project

Let's look at our chatbot 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 the maven project layout.

In src, we can see project sources ( main and test). target is a place where output artifacts are created, whereas project 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 its build.sbt file. It consists of the following code:

The text inside it is a plain Scala snippet.

organization, name, and version are instances of sbt.key. For this point of view, := is a binary operator defined on keys. 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 the sbt tool.

Note

sbt – The original intention for the name, when sbt 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 of sbt here: https://www.scala-sbt.org/1.x/docs/index.html.

Basic sbt Commands

We will now talk about the basic sbt commands.

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

sbt run executes the main function of the project. Therefore, we can try to interact with our chatbot: