Skip to content

Instantly share code, notes, and snippets.

@erichonorez
Last active March 5, 2019 15:35
Show Gist options
  • Save erichonorez/e655e513ea33eb58f9c3e92776410543 to your computer and use it in GitHub Desktop.
Save erichonorez/e655e513ea33eb58f9c3e92776410543 to your computer and use it in GitHub Desktop.
Example of type classes for serialisation
// Start writing your ScalaFiddle code here
case class Book(title: String, author: String)
trait ToJson[A] {
def toJson(a: A): String
}
trait ToXml[A] {
def toXml(a: A): String
}
object BookInstances {
implicit val bookToJsonInstance = new ToJson[Book] {
override def toJson(book: Book): String = s"""{"title": "${book.title}", "author": "${book.author}"}"""
}
implicit val bookToXmlInstance = new ToXml[Book] {
override def toXml(book: Book): String = s"""
| <book>
| <title>${book.title}</title>
| <author>${book.author}</author>
| </book>
""".stripMargin
}
}
object ToJson {
def apply[A : ToJson] = implicitly[ToJson[A]]
object ops {
def toJson[A : ToJson](a: A) = ToJson[A].toJson(a)
}
}
object ToXml {
def apply[A : ToXml] = implicitly[ToXml[A]]
object ops {
def toXml[A : ToXml](a: A) = ToXml[A].toXml(a)
}
}
import ToJson._
import ToJson.ops._
import ToXml._
import ToXml.ops._
import BookInstances._
println(toJson(Book("Hello, World!", "Me")))
println(toXml(Book("Hello, World!", "Me")))
def doSomething[A : ToJson](a: A): String = toJson(a)
println(doSomething(Book("Hello, World!", "Me")))
def doSomethingOther(book: Book): String = toJson(book)
println(doSomethingOther(Book("Hello, World!", "Me")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment