Below you can find example of the ad hoc polymorohism in Scala.
Last active
March 11, 2016 20:33
-
-
Save pvoznenko/60e1036441b80350d865 to your computer and use it in GitHub Desktop.
Example of ad-hoc polymorphism in scala with type classes
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
trait TaxonomyMaker[T] { | |
def toTaxonomyString(value: T): String | |
} | |
case class MakeTax(makeId: Long, genericName: String) | |
case class ModelTax(modelId: Long, makeId: Long, articleTypeId: String, genericName: String) | |
object TaxonomyString { | |
implicit object MakeTaxonomyMaker extends TaxonomyMaker[MakeTax] { | |
def toTaxonomyString(make: MakeTax): String = { | |
import make._ | |
"%d %s".format(makeId, genericName) | |
} | |
} | |
implicit val ModelTaxonomyMaker = new TaxonomyMaker[ModelTax] { | |
def toTaxonomyString(model: ModelTax): String = { | |
import model._ | |
"%d %s".format(makeId, genericName) | |
} | |
} | |
} | |
object util { | |
def printTaxonomy[T: TaxonomyMaker](t: T) = implicitly[TaxonomyMaker[T]].toTaxonomyString(t) | |
} | |
object test { | |
import util._ | |
printTaxonomy(MakeTax) | |
printTaxonomy(ModelTax) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment