Created
January 31, 2022 13:08
-
-
Save vpatryshev/4327bd7c30e7191319c434d383099fa6 to your computer and use it in GitHub Desktop.
How to build an implicit generic converter
This file contains hidden or 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
class Test extends AnyFlatSpec with Matchers { | |
"transformer" should "work" in { | |
// source: https://contributors.scala-lang.org/t/ability-to-force-the-caller-to-specify-a-type-parameter-for-a-polymorphic-method/2116/26 | |
sealed trait NotNothing[-T] | |
object NotNothing { | |
@implicitAmbiguous("inst() method needs a generic parameter type, which is missing") | |
implicit val nothingIsNothing = new NotNothing[Nothing]{} | |
implicit def notNothing[T] = new NotNothing[T] {} | |
} | |
implicit class Transformer(source: String) { | |
def as[T : NotNothing : ClassTag] = { | |
import scala.reflect._ | |
val cls: Class[T] = classTag[T].runtimeClass.asInstanceOf[Class[T]] | |
val cons: Constructor[T] = cls.getDeclaredConstructor(classOf[String]) | |
cons.newInstance(source) | |
} | |
} | |
val a0 = "good A".as[A] | |
val b0 = "good B".as[B] | |
a0.getClass shouldBe classOf[A] | |
b0.getClass shouldBe classOf[B] | |
a0.toString shouldBe "A(good A)" | |
b0.toString shouldBe "B(good B)" | |
} | |
} | |
class Base | |
case class A(val s: String) extends Base | |
case class B(val s: String) extends Base |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment