what are the requirements for a Scala trait/class to be classified as a ADT
fold
? should all implementation of sealed traits/classes be a case
class?
The documentation here says the below
automatic mapping between algebraic data types (ADTs) (encoded in Scala as case classes and sealed traits) and these generic representations.
An algebraic data type is a kind of composite type, i.e., a type formed by combining other types.
Definition taken from Wikipedia
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.
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.
sealed
?sealed is not compulsory, but its good practice.
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).
case
?case is for scala compiler to generate
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
data Closable = File { path :: String, name :: String } | Socket { port :: Int }
But, In Scala sum types are simulated using inheritance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With