Scala-Language.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Scala Language #scala Table of Contents About 1 Chapter 1: Getting started with Scala Language 2 Remarks 2 Versions 2 Examples 3 Hello World by Defining a 'main' Method 3 Hello World by extending App 4 Delayed Initialization 4 Delayed Initialization 4 Hello World as a script 5 Using the Scala REPL 5 Scala Quicksheet 6 Chapter 2: Annotations 8 Syntax 8 Parameters 8 Remarks 8 Examples 8 Using an Annotation 8 Annotating the main constructor 8 Creating Your Own Annotations 9 Chapter 3: Best Practices 11 Remarks 11 Examples 11 Keep it simple 11 Don't pack too much in one expression. 11 Prefer a Functional Style, Reasonably 12 Chapter 4: Case Classes 13 Syntax 13 Examples 13 Case Class Equality 13 Generated Code Artifacts 13 Case Class Basics 15 Case Classes and Immutabilty 15 Create a Copy of an Object with Certain Changes 16 Single Element Case Classes for Type Safety 16 Chapter 5: Classes and Objects 18 Syntax 18 Examples 18 Instantiate Class Instances 18 Instantiating class with no parameter: {} vs () 19 Singleton & Companion Objects 20 Singleton Objects 20 Companion Objects 20 Objects 21 Instance type checking 21 Constructors 23 Primary Constructor 23 Auxiliary Constructors 24 Chapter 6: Collections 25 Examples 25 Sort A List 25 Create a List containing n copies of x 26 List and Vector Cheatsheet 26 Map Collection Cheatsheet 27 Map and Filter Over A Collection 28 Map 28 Multiplying integer numbers by two 28 Filter 28 Checking pair numbers 28 More Map and Filter examples 29 Introduction to Scala Collections 29 Traversable types 30 Fold 31 Foreach 32 Reduce 32 Chapter 7: Continuations Library 34 Introduction 34 Syntax 34 Remarks 34 Examples 34 Callbacks are Continutations 34 Creating Functions That Take Continuations 35 Chapter 8: Currying 37 Syntax 37 Examples 37 A configurable multiplier as a curried function 37 Multiple parameter groups of different types, currying parameters of arbitrary positions 37 Currying a function with a single parameter group 37 Currying 38 Currying 38 When to use Currying 39 A real world use of Currying. 40 Chapter 9: Dependency Injection 42 Examples 42 Cake Pattern with inner implementation class. 42 Chapter 10: Dynamic Invocation 43 Introduction 43 Syntax 43 Remarks 43 Examples 43 Field Accesses 43 Method Calls 44 Interaction Between Field Access and Update Method 44 Chapter 11: Enumerations 46 Remarks 46 Examples 46 Days of the week using Scala Enumeration 46 Using sealed trait and case objects 47 Using sealed trait and case objects and allValues-macro 48 Chapter 12: Error Handling 50 Examples 50 Try 50 Either 50 Option 51 Pattern Matching 51 Using map and getOrElse 51 Using fold 51 Converting to Java 51 Handling Errors Originating in Futures 52 Using try-catch clauses 52 Convert Exceptions into Either or Option Types 53 Chapter 13: Extractors 54 Syntax 54 Examples 54 Tuple Extractors 54 Case Class Extractors 55 Unapply - Custom Extractors 55 Extractor Infix notation 56 Regex Extractors 57 Transformative extractors 57 Chapter 14: For Expressions 59 Syntax 59 Parameters 59 Examples 59 Basic For Loop 59 Basic For Comprehension 59 Nested For Loop 60 Monadic for comprehensions 60 Iterate Through Collections Using a For Loop 61 Desugaring For Comprehensions 61 Chapter 15: Functions 63 Remarks 63 Difference between functions and methods: 63 Examples 63 Anonymous Functions 63 Underscores shorthand 64 Anonymous Functions with No Parameters 64 Composition 64 Relationship to PartialFunctions 65 Chapter 16: Futures 66 Examples 66 Creating a Future 66 Consuming a Successful Future 66 Consuming a Failed Future 66 Putting the Future Together 67 Sequencing and traversing Futures 67 Combine Multiple Futures – For Comprehension 68 Chapter 17: Handling units (measures) 70 Syntax 70 Remarks 70 Examples 70 Type aliases 70 Value classes 70 Chapter 18: Higher Order Function 72 Remarks 72 Examples 72 Using methods as function values 72 High Order Functions(Function as Parameter) 73 Arguments lazy evaluation 73 Chapter 19: If Expressions 75 Examples 75 Basic If Expressions 75 Chapter 20: Implicits 76 Syntax 76 Remarks 76 Examples 76 Implicit Conversion 76 Implicit Parameters 77 Implicit Classes 78 Resolving Implicit Parameters Using 'implicitly' 79 Implicits in the REPL 79 Chapter 21: Java Interoperability 80 Examples 80 Converting Scala Collections to Java Collections and vice versa 80 Arrays 80 Scala and Java type conversions 81 Functional Interfaces for Scala functions - scala-java8-compat 81 Chapter 22: JSON 83 Examples 83 JSON with spray-json 83 Make the Library Available with SBT 83 Import the Library 83 Read JSON 83 Write JSON 83 DSL 83 Read-Write to Case Classes 84 Custom Format 84 JSON with Circe 85 JSON with play-json 85 JSON with json4s 88 Chapter 23: Macros 91 Introduction 91 Syntax 91 Remarks 91 Examples 91 Macro Annotation 91 Method Macros 92 Errors in Macros 93 Chapter 24: Monads 95 Examples 95 Monad Definition 95 Chapter 25: Operator Overloading 97 Examples 97 Defining Custom Infix Operators 97 Defining Custom Unary Operators 97 Chapter 26: Operators in Scala 99 Examples 99 Built-in Operators 99 Operator Overloading 99 Operator Precedence 100 Chapter 27: Option Class 102 Syntax 102 Examples 102 Options as Collections 102 Using Option Instead of Null 102 Basics 103 Example with Map 104 Options in for comprehensions 104 Chapter 28: Packages 106 Introduction 106 Examples 106 Package structure 106 Packages and files 106 Package naming convension 107 Chapter 29: Parallel Collections 108 Remarks 108 Examples 108 Creating and Using Parallel Collections 108 Pitfalls 108 Chapter 30: Parser Combinators 110 Remarks 110 Examples 110 Basic Example 110 Chapter 31: Partial Functions 111 Examples 111 Composition 111 Usage with `collect` 111 Basic syntax 112 Usage as a total function 112 Usage to extract tuples in a map function 113 Chapter 32: Pattern Matching 115 Syntax 115 Parameters 115 Examples 115 Simple Pattern Match 115 Pattern Matching With Stable Identifier 116 Pattern Matching on a Seq 117 Guards (if expressions) 118 Pattern Matching with Case Classes 118 Matching on an Option 119 Pattern Matching Sealed Traits 119 Pattern Matching with Regex 120 Pattern binder (@) 120 Pattern Matching Types 121 Pattern Matching compiled as tableswitch or lookupswitch 121 Matching Multiple Patterns At Once 122 Pattern Matching on tuples 123 Chapter 33: Quasiquotes 125 Examples 125 Create a syntax tree with quasiquotes 125 Chapter 34: Recursion 126 Examples 126 Tail Recursion 126 Regular Recursion 126 Tail Recursion 126 Stackless recursion with trampoline(scala.util.control.TailCalls) 127 Chapter 35: Reflection 129 Examples 129 Loading a class using reflection 129 Chapter 36: Regular Expressions 130 Syntax 130 Examples 130 Declaring regular expressions 130 Repeating matching of a pattern in a string 131 Chapter 37: Scala.js 132 Introduction 132 Examples 132 console.log in Scala.js 132 Fat arrow functions 132 Simple Class 132 Collections 132 Manipulating DOM 132 Using with SBT 133 Sbt dependency 133 Running 133 Running with continous compilation: 133 Compile to a single JavaScript file: 133 Chapter 38: Scaladoc 134 Syntax 134 Parameters 134 Examples 135 Simple Scaladoc to method 135 Chapter 39: scalaz 136 Introduction 136 Examples 136 ApplyUsage 136 FunctorUsage 136 ArrowUsage 137 Chapter 40: Scope 138 Introduction 138 Syntax 138 Examples 138 Public (default) scope 138 A private scope 138 A private package-specific scope 139 Object private scope 139 Protected scope 139 Package protected scope 139 Chapter 41: Self types 141 Syntax 141 Remarks 141 Examples 141 Simple self type example 141 Chapter 42: Setting up Scala 142 Examples 142 On Linux via dpkg 142 Ubuntu Installation via Manual Download and Configuration 142 Mac OSX via Macports 143 Chapter 43: Single Abstract Method Types (SAM Types) 144 Remarks 144 Examples 144 Lambda Syntax 144 Chapter 44: Streams 145 Remarks 145 Examples 145 Using a Stream to Generate a Random Sequence 145 Infinite Streams via Recursion 145 Infinite self-referent stream 146 Chapter 45: String Interpolation 147 Remarks 147 Examples 147 Hello String Interpolation 147 Formatted String Interpolation Using the f Interpolator 147 Using expression in string literals 147 Custom string interpolators 148 String interpolators as extractors 149 Raw String Interpolation 149 Chapter 46: Symbol Literals 151 Remarks 151 Examples 151 Replacing strings in case clauses 151 Chapter 47: synchronized 153 Syntax 153 Examples 153 synchronize on an object 153 synchronize implicitly on this 153 Chapter 48: Testing with ScalaCheck 154 Introduction 154 Examples 154 Scalacheck with scalatest and error messages 154 Chapter 49: Testing with ScalaTest 157 Examples 157 Hello World Spec Test 157 Spec Test Cheatsheet 157 Include the ScalaTest Library with SBT 158 Chapter 50: Traits 159 Syntax 159 Examples 159 Stackable Modification with Traits 159 Trait Basics 160 Solving the Diamond Problem 160 Linearization 161 Chapter 51: Tuples 164 Remarks 164 Examples 164 Creating a new Tuple 164 Tuples within Collections 164 Chapter 52: Type Classes 166 Remarks 166 Examples 166 Simple Type Class 166 Extending a Type Class 167 Add type class functions to types 168 Chapter 53: Type Inference 170 Examples 170 Local Type Inference 170 Type Inference And Generics 170 Limitations to Inference 170 Preventing inferring Nothing 171 Chapter 54: Type Parameterization (Generics) 173 Examples 173 The Option type 173 Parameterized Methods 173 Generic collection 173 Defining the list of Ints 174 Defining generic list 174 Chapter 55: Type Variance 175 Examples