5

考虑以下相对简单的代码:

import scala.deriving.Mirror

trait TC[A]:
  def show: A
object TC:
  inline def derived[A](using m: Mirror.ProductOf[A]): TC[A] = new TC[A]:
    override def show: A =
      val p: Product = new Product:
        def canEqual(that: Any): Boolean = true
        def productArity: Int = 1
        def productElement(n: Int): Any = 1
      m.fromProduct(p)

sealed trait T
case class C(x: Int) extends T derives TC
case object C // If I remove this line, then no exception will be thrown

@main
def main: Unit =
  println(summon[TC[C]].show)

运行它会导致以下异常:

java.lang.ClassCastException: class nn.C$ cannot be cast to class nn.C (nn.C$ and nn.C are in unnamed module of loader sbt.internal.LayeredClassLoader @48aba6c1)
    at nn.C$$anon$1.show(MarshalerMacrosTest.scala:14)
    at nn.C$$anon$1.show(MarshalerMacrosTest.scala:9)
    at nn.MarshalerMacrosTest$package$.main(MarshalerMacrosTest.scala:22)
    at nn.main.main(MarshalerMacrosTest.scala:20)

但如果我删除case object C,那么一切都会好起来的。异常发生在m.fromProduct(p)。如果case object C存在,m.fromProduct(p)则返回此对象而不是 type 的实例C。知道为什么会这样吗?什么是最好的解决方法?

4

0 回答 0