Scala: implicitly convert parameter to implicit class variant

How to implicitly convert option [A] to Option [B], where B is the implicit class A?

The following code only works converter1, but the return type is not general:

implicit class Test(val i: Int)

implicit def converter0[A, B](opt: Option[A])(implicit f: A => B): Option[B] = {
  opt.map(f)
}

implicit def converter1[A](opt: Option[A])(implicit f: A => Test): Option[Test] = {
  opt.map(f)
}

implicit def converter2[B](opt: Option[Int])(implicit f: Int => B): Option[B] = {
  opt.map(f)
}

val b: Option[Int] = Option(1)
val a: Option[Test] = b
+4
source share

Source: https://habr.com/ru/post/1681739/


All Articles