— Essential Scala: Six Core Concepts for Learning Scala —
Adam Rosien @arosien Underscore https://underscore.io
Can you also read this, you back there?
There are very cool seats up front.
- Are you not a beginner?
- Please let the beginners speak the most!
- Scala is complex?
- Self types
- Type bounds
- Existential types
- Trait stacks
- Overloading
- Implicit conversions
- It doesn’t have to be this way
- 6 concepts
- Expressions, types, & values
- Objects and classes
- Algebraic data types
- Structural recursion
- Sequencing computation
- Type classes
- Goal: translate data descriptions into code
- Model data with logical ors and logical ands
- Two patterns: product types (and) sum types (or)
- Product type: A has a B and C
- Sum type: A is a B or C
- Sum and product together make algebraic data types
-> scala code
- Summary
- Structure data with logical ands and ors
- These are called algebraic data types
- Code follows immediately from structure of the data
- Goal: transform algebraic data types
- Structure of the code follows structure of the data
- Two (sub-)patterns: pattern matching and polymorphism
-> Implement Calculation.add(value: Int): Calculation = ???
- Summary
- Processing algebraic data types immediately follows from the structure of the data
- Can choose between pattern matching and polymorphism
- Pattern matching (within the base trait) is usually preferred
- Goal: patterns for sequencing computations
- Functional programming is about transforming values
- That is all you can do without introducing side- effects
- A => B => C
- This is sequencing computations
- Three patterns: fold, map, and flatMap
- fold
- A => B
- Abstraction over structural recursion
-> Convert user to JSON
- map
- F[A] => (A => B) => F[B]
-> Get user from database (might not be a user): Result[User] -> Get order for user (might not be an order): User => Result[Order]
- flatMap
- F[A] => (A => F[B]) => F[B]
-> Get user by id: UserId => Result[User] -> Get user’s order: User => Result[Order] -> Transform order to JSON: (Order => Json) => Result[Json] -> Send JSON: Result[Json] => Response
- Summary
- Standard patterns for sequencing computations
- fold is general transformation for algebraic data types
- map: F[A] => (A => B) => F[B]
- flatMap: F[A] => (A => F[B]) => F[B]
- You can teach monads in an introductory course!
- Ad-hoc polymorphism
- Break free from your class oppressors!
- Concerns that cross class hierarchy
- E.g. serialize to JSON
- Common behaviour without (useful) common type
- Abstract behaviour to a type class
- Can implement type class instances in ad-hoc manner
- Scala is simple
- 3 patterns are 90% of code
- 4 patterns are 99% of code
- Program design in Scala is systematic -> Be like keyboard cat!
- Get our “Essential Scala” book, it’s free! https://underscore.io/books/essential-scala/
- https://underscore.io/training/