Skip to content

Instantly share code, notes, and snippets.

sealed trait Shape
case class Circle(radius: Int) extends Shape
case class Rectangle(width: Int, height: Int) extends Shape
// 'match' keyword allows us to pattern match on a
// specific option of the sum type
def area(shape: Shape): Double = shape match {
case Circle(r) => math.Pi * r * r
-- The | can be read as 'or'
data Shape = Circle Int | Square Int
-- Alternatively
data Shape
= Circle { radius :: Int }
| Square { side :: Int }
// Scala doesn't have a nice syntax for sum types so
// it looks like a familiar OOP inheritance tree.
sealed trait Shape
// But don't get confused: the 'extends' here stands for 'is'
// relationship, not in a sense of 'extends and overrides methods'.
// It only says that when you create a Circle it will be of type 'Shape'
case class Circle(radius: Int) extends Shape
case class Square(side: Int) extends Shape
-- Person is a product type consisting of 3 fields
data Person = Person
{ name :: String
, age :: Int
, address :: Address
}
-- Address is a product type on its own
data Address = Address
{ country :: String
// Person is a product type consisting of 3 fields
case class Person(name: String, age: Int, address: Address)
// Address on its own also is a product type
case class Address(country: String, city: String, street: String)
// In order to create a Point you have to provide all 3 arguments
case class Point(x: Double, y: Double, z: Double)
bob = Person "Bob" 42
olderBob = bob { age = 43 }
val bob = Person("Bob", 42)
// .copy provided by the 'case class'
val olderBob = bob.copy(age = 43)
data Person = Person
{ name :: String
, age :: Int
, address :: Address
}
-- Using type constructor
person = Person "Bob" 42
-- Or using records notation
case class Person(name: String, age: Int)
// Using type constructor
val person = Person("Bob", 42)
// Accessing fields
val personsAge = person.age
data Person = Person String Int
-- OR
data Person = Person
{ name :: String
, age :: Int
, address :: Address
}