On Github fedeoasi / scala-presentation
Created by Federico Caimi / @fedeoasi Backstop Solutions Group
Code is suddenly easier to test, debug, and run in parallel!
OOP is good at structuring programs
Interfaces, Classes, Encapsulation, Delegation, SingletonFP is good at isolating state change
Immutability, Repeatability, ConcurrencyScala Combines the two:
val ten = 10 //ten is an immutable value of type Int var number = 2 //number is mutable number += 1 //number is now 3 def sum(a: Int, b: Int): Int = a + b def sumThree(a: Int): Int = sum(a, 3) val numbers = 1 to 4 //Range(1, 2, 3, 4) val doubles = numbers.map(_ * 2) //Range(2, 4, 6, 8) val squares = numbers.map(n => n * n) //Range(1, 4, 9, 16) val summedThree = numbers.map(sumThree) //Range(4, 5, 6, 7)
Option[A] is a container type and can have two values: Some[A] and None.
class User(val username: String, val email: Option[String]) val users = Seq( new User("user1", Some("user1@gmail.com")), new User("user2", None), new User("user3", Some("user3@gmail.com")) ) def sendMessage(email: String, message: String) = println(s"Sending email to $message") users.foreach { u => u.email match { case Some(email) => sendMessage(email, "Welcome to MyApp") case None => } }
Your code will be safer as the compiler will force you to think about the None case.
case class Person(firstName: String, lastName: String, birthDate: LocalDate)
With just a little typing, we get a lot of things:
Goal: Have fun processing collections in Scala
Possible Side Effect: Learn something interesting about the CTA
Code on Github