loicdescotte
10/3/2013 - 8:09 AM

Type class example

Type class example

scala> List(1,2,3).sum

res0: Int = 6

scala> case class Color(name: String)

defined class Color

scala> List(Color("red"), Color("blue"), Color("Yellow")).sum

<console>:10: error: could not find implicit value for parameter num: Numeric[Color]
              List(Color("red"), Color("blue"), Color("Yellow")).sum //<-- Need to define a way to use Color like numerics

scala> 
     //Just a simple and ugly Numeric[Color] implementation to sum colors
      implicit object ColorNumeric extends math.Numeric[Color] {
              def plus(x: Color, y: Color) = if(x.name != "") Color(x.name + " and " + y.name) else Color(y.name)
              def compare(x:Color,y:Color) = throw new Error
              def minus(x: Color, y: Color) = throw new Error
              def times(x: Color, y: Color) = throw new Error
              def negate(x: Color): Color = throw new Error
              def fromInt(x: Int) = if(x ==0) new Color("") else throw new Error
              def toInt(x: Color) = throw new Error
              def toLong(x: Color) = throw new Error
              def toFloat(x: Color) = throw new Error
              def toDouble(x: Color) = throw new Error
      }
     

defined module ColorNumeric
//this implicit object can be imported and used wherever we want

scala> List(Color("red"), Color("blue"), Color("Yellow")).sum

res3: Color = Color(red and blue and Yellow) // Hurrah!