Learn the latest version of Scala through simple, practical examples. This book introduces you to the Scala programming language, its object-oriented and functional programming characteristics, and then guides you through Scala constructs and libraries that allow you to assemble small components into high-performance, scalable systems. Beginning Scala 3 explores new Scala 3 language features such as Top-level declarations, Creator applications, Extension methods to add extra functionality to existing types, and Enums. You will also learn new ways to manipulate types via Union types, intersection, literal, and opaque type aliases. Additionally, you’ll see how Implicits are replaced by given and using clauses. After reading this book, you will understand why Scala is judiciously used for critical business applications by leading companies such as Twitter, LinkedIn, Foursquare, the Guardian, Morgan Stanley, Credit Suisse, UBS, and HSBC – and you will be able to use it in your own projects. What You Will Learn Get started with Scala 3 or Scala language programming in general Understand how to utilitze OOP in Scala Perform functional programming in Scala Master the use of Scala collections, traits and implicits Leverage Java and Scala interopability Employ Scala for DSL programming Use patterns and best practices in Scala Who This Book Is For Those with a background in Java and/or Kotlin who are new to Scala. This book is also for those with some prior Scala experience who want to learn Scala version 3. Table of Contents 5 About the Authors 13 About the Technical Reviewer 15 Acknowledgments 16 Introduction 17 Chapter 1: Getting Started with Scala 21 Why Use Scala? 21 Migrating to Scala 3 23 History 25 Installing Scala Tools 28 Installing Java JDK 28 Installing Scala 29 Using Brew 30 Using Coursier 30 Installing SBT 31 Installing the IDE 32 Running Code Examples 33 Using an IDE 33 Manually Using the REPL 34 Running Little Blocks 35 Compiling and Running Files 36 Online Tools 38 Summary 40 Chapter 2: Basics of Scala 41 Variables 41 Scala Type Hierarchy 44 Any, AnyVal, and AnyRef Types 45 Numeric Types 45 Types and Range 45 Conversion 46 Format 47 Boolean 47 Char 48 Unit 48 Strings 48 Interpolation 49 Compare 49 Split 50 Replace 50 Special Characters 50 Other Methods 51 Date 52 Format 53 Arrays 54 Lists 56 Null 57 Nothing 57 Functions 58 Control Structures 59 if/then/else Expressions 59 for Loops 61 while Loops 62 match Expressions 63 try/catch/finally Blocks 64 Comments 65 Running Code Without the REPL 65 Keywords 67 Summary 69 Chapter 3: Object-Oriented Modeling 71 Concepts of OOP 71 From Concepts to Concrete Things 74 Classes 76 Fields 78 Constructors 79 Visibility of the Fields 80 Auxiliary Constructors 81 Providing Default Values 82 Private Constructor 82 Methods 83 Order 83 Invoking Methods 84 Override Default Methods 84 toString 84 equals 85 Inheritance 85 Inner Classes 87 Value Classes 87 Packages and Imports 89 Multiple Imports 90 Exclude Class 90 Objects 91 Defining Singletons 91 Companion Objects 92 Static Factory 93 Opaque Types 93 Export Clauses 95 Summary 96 Chapter 4: Functional Programming 98 What Is Functional Programming? 99 Pure Functions 100 Side Effects 101 Referential Transparency 101 Expression-Oriented Programming 102 Functions, Lambdas, and Closures 103 Function Literal/Anonymous Function 104 First-Class Functions and Higher-Order Functions 107 Functions as Variables 108 Functions as Parameters 109 Returning a Function 110 Closure 110 Partially Applied Functions 111 Curried Functions 112 Function Compositions 113 Function Error Handling 115 Tail Calls and Tail Call Optimization 116 Call-by-Name, Call-by-Value, and General Laziness 118 Functional Structures 120 Sequence 120 Maps 121 Sets 123 Tuples 124 Options 125 Instantiating 125 Chained Methods 126 Functional Operations 126 Traversing 126 Mapping 127 Filtering 127 Summary 128 Chapter 5: Pattern Matching 129 Basic Pattern Matching 129 Matching Any Type 133 Testing Data Types 134 Pattern Matching in Lists 135 Pattern Matching and Lists 136 Compiler Optimization 138 Tableswitch 139 Lookupswitch 139 Considerations 140 Pattern Matching with the Matchable Trait 140 Pattern Matching and Case Classes 141 Nested Pattern Matching in Case Classes 143 Pattern Matching as Functions 144 Pattern Matching on Regular Expressions 146 Object-Oriented and Functional Tensions 147 Shape Abstractions 148 Summary 152 Chapter 6: Scala Collections 153 Scala Collection Hierarchy 154 The scala.collection Package 155 Sequences 156 Sets 157 Map 157 The scala.collection.immutable package 158 Immutable Sequence 160 Immutable Set 160 Immutable Map 161 The scala.collection.mutable package 161 Using Immutable Collection Classes 165 Vector 166 List[T] 168 Getting Functional 169 Transformation 170 Reduxio 172 Look Ma, No Loops 174 Range 176 Stream or LazyList 176 Tuples 178 Map[K, V] 179 Mutable Collections 182 Mutable ArrayBuffer 183 Mutable Queue 184 Mutable Stack 185 Performance of the Collections 186 Summary 188 Chapter 7: Traits and Enums 190 Traits 190 Using Traits as Mixins 192 Traits and Class Hierarchies 196 Conflicts of Method Names 202 Limiting the Use of a Trait 203 Limiting Access by Class 203 Limiting Access by Method 204 Type Parameters or Type Members 205 Passing Parameters on Traits 206 Enumerations 206 Algebraic Data Types in Enums 208 Union and Intersection Types 210 Summary 212 Chapter 8: Scala Type System 213 Unified Type System 213 Type Parameterization 216 Variance 217 Covariant Parameter Types 218 Contravariant Parameter Types 219 Invariant Parameter Types 221 Rules of Variance 224 Type Bounds 224 Upper Type Bounds 224 Lower Type Bounds 226 Extension Methods 226 Scala 2 Implicit Class 227 Scala 3 Given/Using Clauses 230 Implicit Conversions 231 Givens and Imports 231 Using Clauses 232 Summary 233 Chapter 9: Scala and Java Interoperability 234 Scala at a Glance 234 Translating Java Classes to Scala Classes 235 Translating Java Imports into Scala Imports 237 Translating Multiple Constructors 238 JavaBean Specification-Compliant Scala Classes 241 Java Interfaces and Scala Traits 243 Java Static Members and Scala Objects 245 Handling Exceptions 246 Java Optional and Scala Option 248 Use Java Collections in Scala 249 Summary 251 Chapter 10: DSL and Parser Combinator 252 A Closer Look at DSLs 252 Internal DSLs 254 External DSLs 260 Summary 260 Chapter 11: Simple Build Tool 261 Getting Started with SBT 263 Why SBT? 263 Installing SBT 264 General Commands 264 Creating a Hello World Project 265 Project Structure 267 build.sbt 268 Project Folder 270 Src Folder 270 Build Definition 271 LibraryDependencies and Resolvers 272 Plugins 274 Summary 275 Chapter 12: Creating Web Applications 276 Architecture Types 276 Setting Up the Application 283 Application Flow 286 Router 287 Controller 288 Model 288 View 289 Rest Application 289 Defining the Endpoints 289 Layers in the Application 292 Custom Error Handler 296 Summary 298 Chapter 13: Testing Your Code 299 Testing with ScalaTest 299 Writing Your First Test 301 Ignoring the Execution of the Test 303 Other Ways of Declaring the Test 304 Using Matchers to Validate Results 307 Tagging Your Test 308 Before and After Methods 310 Summary 311 Chapter 14: Scala Best Practices 312 General Best Practices 312 Recognizing the Functional Style 313 Writing Pure Functions 315 Leveraging Type Inferencing 316 Think Expressions 317 Focusing on Immutability 319 Keeping Methods Short 320 Using Options Instead of Null Testing 321 Refactor Mercilessly 322 Composing Functions and Classes 324 Summary 324 Index 326