Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created October 3, 2019 10:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancellu/5fd36102f1da548841483327501a9d48 to your computer and use it in GitHub Desktop.
Save fancellu/5fd36102f1da548841483327501a9d48 to your computer and use it in GitHub Desktop.
Example usage of Cats typeclasses that should be easy enough to follow
Using default instances
false
false
Using custom Eq instance
true
Comparisons
0
1
-1
Show
Item name:Cat price:10.0
list is List(Item(Ant,1.0), Item(Mouse,5.0), Item(Cat,10.0), Item(Dog,20.0))
list is List(Item name:Ant price:1.0, Item name:Mouse price:5.0, Item name:Cat price:10.0, Item name:Dog price:20.0)
Enum example
false
true
a man is Gender Male
import cats._
import cats.data._
import cats.implicits._
object Typeclasses extends App {
case class Item(name: String, price: Double)
object Item {
// note we are using SAM support to define these instances
// https://gist.github.com/fancellu/713602e68746336b1dc41c9dab85d4a5
implicit val eq: Eq[Item] = (x: Item, y: Item) => x == y
implicit val order: Order[Item] = (x: Item, y: Item) => x.price.compare(y.price)
implicit val show: Show[Item] = (x: Item) => s"Item name:${x.name} price:${x.price}"
}
val cat = Item("Cat", 10)
val mouse = Item("Mouse", 5)
val dog = Item("Dog", 20)
val ant = Item("Ant", 1)
println("Using default instances")
println(cat === Item("Cat", 1000))
println(cat === mouse)
println("Using custom Eq instance")
{ //in scope Eq only cares about name
implicit val ItemEqName: Eq[Item] = (x: Item, y: Item) => x.name == y.name
println(cat === Item("Cat", 1000))
}
println("Comparisons")
println(cat compare cat)
println(cat compare mouse)
println(cat compare dog)
println("Show")
println(cat.show)
val items = List(cat, mouse, dog, ant).sorted // sorted by Item.order, i.e. price
println(s"list is $items")
//vs
println(show"list is $items")
println("Enum example")
sealed trait Gender
object Gender {
private case object Male extends Gender
private case object Female extends Gender
private case object Unknown extends Gender
// the horror of enums in Scala, sorry, need to upcast due to Eq nonvariant subtyping
def male: Gender = Male
def female: Gender = Female
def unknown: Gender = Unknown
implicit val eq: Eq[Gender] = (x: Gender, y: Gender) => x == y
implicit val show: Show[Gender] = (x: Gender) => s"Gender $x"
}
println(Gender.male === Gender.female)
println(Gender.male === Gender.male)
println(show"a man is ${Gender.male}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment