Created
August 20, 2014 10:50
-
-
Save fiadliel/4e3f863ac785e4421f61 to your computer and use it in GitHub Desktop.
Typeclass pattern using Scala implicit 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
package typeclass_example | |
case class Example(a: Int, b: String) |
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
package typeclass_example | |
object Main extends App { | |
val a = Example(1, "a") | |
// serialize() does not exist - looks for an implicit | |
// conversion to something that does have this method. | |
// implicit class SerializerEnhancer in package object | |
// is valid for this use. | |
val serialized = a.serialize | |
println(serialized) | |
} |
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
/** Package object for typeclass_example | |
* | |
* All definitions here are in scope for the package. | |
*/ | |
package object typeclass_example { | |
/** Pimped class for any T, offering a serialize() method. | |
* | |
* Available in implicit scope for all code in package | |
* typeclass_example. | |
* It wraps a "T", creating a new SerializerEnhancer object. | |
* Then serialize can be called on this, which will look for | |
* a Serializer[T] matching the "T" type of the original object. | |
*/ | |
implicit class SerializerEnhancer[T](o: T) { | |
def serialize(implicit serializer: Serializer[T]): String = { | |
serializer.serialize(o) | |
} | |
} | |
/** Serializer for an "Example" type. | |
* | |
* It is an implicit with type Serializer[Example] and | |
* implements the abstract definitions in Serializer[T] for | |
* this type. | |
*/ | |
implicit val exampleSerializer = new Serializer[Example] { | |
def serialize(e: Example): String = s"${e.a} ${e.b}" | |
} | |
} |
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
package typeclass_example | |
trait Serializer[T] { | |
def serialize(o: T): String | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment