Common
A simple example for scala type-class implicits
13. March 2017
0

I just read a nice article about implicits in Scala which gives a good and understandable overview about the topic. See: http://www.lihaoyi.com/post/ImplicitDesignPatternsinScala.html

trait Jsonable[T] {
  def serialize(t: T): Json
}

object Jsonable {

  implicit object SeqOfStringJsonable extends Jsonable[Seq[String]] {
    override def serialize(t: Seq[String]): Json = Json.StrArray(t.map(Json.Str))
  }

  implicit object StringJsonable extends Jsonable[String] {
    override def serialize(t: String): Json = Json.Str(t)
  }

  implicit object DoubleJsonable extends Jsonable[Double] {
    override def serialize(t: Double): Json = Json.Number(t)
  }

  implicit object IntJsonable extends Jsonable[Int] {
    override def serialize(t: Int): Json = Json.Number(t.toDouble)
  }
}

sealed trait Json

object Json {
  case class Str(s: String) extends Json
  case class Number(v: Double) extends Json
  case class StrArray(v: Seq[Str]) extends Json
}

def convertToJson[T](x: T)(implicit converter: Jsonable[T]): Json = converter.serialize(x)

convertToJson(3)
convertToJson(1.0)
convertToJson("Hallo Welt")
convertToJson(Seq("Hallo", "Welt"))