juan_gandhi: (Default)
 gist
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

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

July 2025

S M T W T F S
  12345
6789 1011 12
13141516171819
20212223242526
2728293031  

Syndicate

RSS Atom

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 13th, 2025 12:41 am
Powered by Dreamwidth Studios