Skip to content

Instantly share code, notes, and snippets.

@felipeeflores
Last active August 29, 2018 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipeeflores/cdc5821c370717ea6694d394fc464299 to your computer and use it in GitHub Desktop.
Save felipeeflores/cdc5821c370717ea6694d394fc464299 to your computer and use it in GitHub Desktop.
Presenter notes and examples for TypesExercises.scala
// case classes
/*
You can do pattern matching on it,
You can construct instances of these classes without using the new keyword,
All constructor arguments are accessible from outside using automatically generated accessor functions,
The toString method is automatically redefined to print the name of the case class and all its arguments,
The equals method is automatically redefined to compare two instances of the same case class structurally rather than by identity.
The hashCode method is automatically redefined to use the hashCodes of constructor arguments.
*/
// Notice how there is no need for using the `new` clause
val john = Person(name = "John Kane", age = 35)
// case classes are inmutable
// john.age = 25 <- Compiler error
//
//case classes are compared by structure not by memory
> val person2 = Person(name = "John Kane", age = 35)
> john == person2
> res0: Boolean = true
// copying, you can create shallow copies
scala> val twin = john.copy(name = "Gilberto")
twin: fundamentals.level02.TypesExercises.Person = Person(Gilberto,35)
scala> john == twin
res1: Boolean = false
// pattern matching
// technique to check a value against a pattern, a way to deconstruct the elements that form a value
// You can match a case class constructor
// You can use literal values, match any value or use guards, you can as well ignore values
scala> val checker: Person => String = {
| case Person("Gilberto", age) => s"Gilberto is $age years old"
| case Person(name, age) if age > 18 => s"$name is an adult of $age years old"
| case Person(_, age) => s"Another person is $age years old"
| }
scala> checker(john)
res3: String = John Kane is an adult of 35 years old
scala> checker(twin)
res4: String = Gilberto is 35 years old
scala> val minor = Person("Felipe", 17)
minor: fundamentals.level02.TypesExercises.Person = Person(Felipe,17)
scala> checker(minor)
res5: String = Another person is 17 years old
// ADTs
// This technique helps you make invalid states/values irrepresentable in your programs
// Sum types: A "sum type" is any type that has multiple possible representations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment