Skip to content

Instantly share code, notes, and snippets.

@rupeshtr78
Created November 1, 2020 21:41
Show Gist options
  • Save rupeshtr78/dfd57f74d350e36de3a4e1a5d858ee66 to your computer and use it in GitHub Desktop.
Save rupeshtr78/dfd57f74d350e36de3a4e1a5d858ee66 to your computer and use it in GitHub Desktop.
package scalabeginner.algebraicdatatypes
object AlgebraicDataTypes extends App {
//Sum ADT
sealed abstract trait Month
case object January extends Month
case object February extends Month
case object March extends Month
case object April extends Month
case object May extends Month
case object June extends Month
case object July extends Month
case object August extends Month
case object September extends Month
case object October extends Month
case object November extends Month
case object December extends Month
object Month {
def toInt(month: Month): Int =
month match { // exhaustive matching possible due to sealed trait
case January => 1
case February => 2
case March => 3
case April => 4
case May => 5
case June => 6
case July => 7
case August => 8
case September => 9
case October => 10
case November => 11
case December => 12
case _ => 0
}
}
val thisMonth:Month = November
println(thisMonth)
val monthNum = Month.toInt(thisMonth)
println(monthNum)
//Product ADT
sealed case class RGB(red: Int, green: Int, blue: Int)
val magenta = RGB(10,200,255)
//Hybrid
case class Point(x: Double, y: Double)
sealed abstract trait Shape
case class Circle(centre: Point, radius: Double) extends Shape
case class Rectangle(topLeft: Point, height: Double, width:Double) extends Shape
object Shape {
def area(shape: Shape): Double =
shape match {
case Circle(Point(x, y), radius) => Math.PI *
Math.pow(radius, 2)
case Rectangle(_, h, w) => h * w
}
}
val circleArea = Shape.area(Circle(Point(0,0),10))
val rectangle = Rectangle(Point(6, 7), 10, 10)
val rectangleArea = Shape.area(rectangle)
println(circleArea)
println(rectangleArea)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment