Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //typeclass example
- //Note : List already has a sum method working the same way
- //List(1,2,3).sum returns 6
- //but this example is simpler
- trait Summable[T] {
- def sum(a: T, b: T): T
- }
- //default instances
- object Summable {
- implicit val intSummable: Summable[Int] = (a: Int, b: Int) => a +b
- implicit val stringSummable: Summable[String] = (a: String, b: String) => a +b
- }
- //add sumAll method to Scala List type
- implicit class ListWithSumAll[T](list: List[T]){
- def sumAll()(implicit summable: Summable[T]): T = {
- list.reduceLeft((sum, element) => summable.sum(sum, element))
- }
- }
- List(1,2,3).sumAll //6
- // add your instances here
- case class Color(red: Int, green: Int, blue: Int)
- implicit val colorSummable: Summable[Color] = (c1: Color, c2: Color) => {
- val red = (c1.red + c2.red) /2
- val green = (c1.green + c2.green) /2
- val blue = (c1.blue + c2.blue) /2
- Color(red, blue, green)
- }
- List(Color(10,10,10), Color(200, 255, 10), Color(20, 55, 1)).sumAll // Color(62,66,32)
Add Comment
Please, Sign In to add comment