trait Presenter[A] {
def present(a: A): String
}
implicit val stringPresenter = new Presenter[String] {
def present(a: String): String = a
}
implicit val intPresenter = new Presenter[Int] {
def present(a: Int): String = a.toString
}
case class Value(s: String)
implicit def present[A](v: A)(implicit presenter: Presenter[A]): Value =
Value(presenter.present(v))
}
def format(v: Value*): String =
v.map(_.s).mkString("\n")
format(1, "a", "c")
format(1, "a", "c", Some(123))
implicit def optionPresenter[A](implicit presenter: Presenter[A]) = new Presenter[Option[A]] {
def present(a: Option[A]): String =
a match {
case Some(v) => presenter.present(v)
case None => "Nothing here"
}
}
And to be honest I have absolutely no clue how to do this. I wrote additional implicit which looks like that
implicit def optionPresenter[A](implicit presenter: Presenter[A]) = new Presenter[Option[A]] { def present(a: Option[A]): String = a match { case Some(v) => presenter.present(v) case None => "Nothing here" } }
But it doesn't work since there is no Presenter instance of presenter for Option[String], only method which should create it.
Value.present(Some(123)) // will not work
Value.present(Some(123): Option[Int]) // works
....scala:41: could not find implicit value for parameter presenter: Presenter[Some[Int]]
Value.present(Some(123)) // will not work
^I hope you'll agree that optionPresenter does not return a value of type Presenter[Some[Int]]!
Do you guys have any idea how to make this work ?