An algebraic data type is a kind of composite type, i.e., a type formed by combining other types.
Definition taken from Wikipedia
What is product type?
class Person(name: String, age: Int)
Person type is formed by combining name and age types.
You need both name and age to construct the Person type. Meaning Person is the product (algebraic product, not mathematical product) of name and age types.
What is sum type?
trait Closable
class File(path: String) extends Closable
class Socket(port: Int) extends Closable
Closable can be created by either File or Socket. One of them is enough for making an instance of Closable. File and Socket are called sum types.
Why sealed
?
sealed is not compulsory, but its good practice.
What happens when you use sealed
?
sealed trait Closable
class File(path: String) extends Closable
class Socket(port: Int) extends Closable
You cannot declare another sub type of Closable in another file. All the sub types have to present in single file. This stops pattern matching from giving Match Error. All subtypes with be in one file and only library author will be able to add more subtypes (in case of library).
Why case
?
case is for scala compiler to generate
- Class companion object with apply, applySeq, unapply and unapplySeq methods
- Also equals, copy, toString etc are also generate automatically
- Its helps in de-structuring the case class when patten matching.
What about fold
?
fold is entirely another concept it has nothing to do with ADTs
Finally, ADTs look like this
sealed trait Closable
case class File(path: String, name: String) extends Closable
case class Socket(port: Int) extends Closable
also there can be abstract class as well
sealed abstract class Closable
case class File(path: String, name: String) extends Closable
case class Socket(port: Int) extends Closable
Haskell ADTs
data Closable = File { path :: String, name :: String } | Socket { port :: Int }
But, In Scala sum types are simulated using inheritance