Last active
June 18, 2018 08:42
-
-
Save loicdescotte/167219163b22f96679f620faf7ad6525 to your computer and use it in GitHub Desktop.
Scala : make a class implement a trait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//example with Generic trait | |
trait Summable[T] { | |
def sumWith(other: T): T | |
} | |
implicit class StringSummable(s: String) extends Summable[String]{ | |
def sumWith(other: String): String = s + other | |
} | |
//add sumAll method to Scala List type | |
implicit class ListWithSumAll[T](list: List[T]){ | |
def sumAll()(implicit ev: T => Summable[T]): T = { | |
list.reduceLeft((sum, element) => sum.sumWith(element)) | |
} | |
} | |
List("1","2","3").sumAll //123 | |
// add your extensions here | |
case class Color(red: Int, green: Int, blue: Int) | |
implicit class ColorSummable(c: Color) extends Summable[Color] { | |
def sumWith(other: Color): Color = { | |
val red = (c.red + other.red) /2 | |
val green = (c.green + other.green) /2 | |
val blue = (c.blue + other.blue) /2 | |
Color(red, blue, green) | |
} | |
} | |
List(Color(10,10,10), Color(200, 255, 10), Color(20, 55, 1)).sumAll // Color(62,66,32) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Light alternative to typeclasses : make a class implement a trait in Scala | |
trait Player { | |
def score: Int | |
} | |
case class Person(name: String) | |
val john = new Person("john") | |
def displayScore(player: Player): Unit = { | |
println("score : " + player.score) | |
} | |
implicit class PersonWithScore(person: Person) extends Player { | |
def score: Int = 0 | |
} | |
displayScore(john) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment