Advertisement
fra834

Scoped Typeclasses For The Typeclass God

Aug 22nd, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.78 KB | None | 0 0
  1. object ShapeyThings {
  2.   trait ShapeLike[A] {
  3.     def area(shape: A): Int
  4.   }
  5. }
  6.  
  7. object ShapesForTheShapeGod {
  8.  
  9.   case class Rectangle(x: Int, y: Int)
  10.   object Rectangle {
  11.     import ShapeyThings._
  12.     implicit object RectangleShape extends ShapeLike[Rectangle] {
  13.       def area(shape: Rectangle) = shape.x * shape.y
  14.     }
  15.   }
  16.  
  17.   case class Square(a: Int)
  18.   object Square {
  19.     import ShapeyThings._
  20.     implicit object SquareShape extends ShapeLike[Square] {
  21.       def area(shape: Square) = shape.a * shape.a
  22.     }
  23.   }
  24. }
  25.  
  26. object WorkingScope {
  27.   import ShapeyThings._
  28.   import ShapesForTheShapeGod.Square
  29.  
  30.   def doSomething[A : ShapeLike](shape: A) =  println(implicitly[ShapeLike[A]].area(shape))
  31.  
  32.   def run = doSomething(new Square(3))
  33. }
  34.  
  35. WorkingScope.run //9
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement