考虑以下示例:
sealed trait Granularity
object Granularity {
case object Full extends Granularity
sealed trait Partial extends Granularity {
type GranularityKey
}
case object StringGranularity extends Partial {
override type GranularityKey = String
}
}
sealed trait Test{
type T <: Granularity
}
object Test {
type Aux[TT <: Granularity] = Test{ type T = TT }
case object Cmp extends Test{
override type T = StringGranularity.type
}
case object Fll extends Test{
override type T = Full.type
}
}
case class Tst[Gran <: Partial, T <: Test.Aux[Gran]](t: T#T#GranularityKey)
^
|___Advanced language feature: reflective call关于某些反射呼叫的想法信号出现在类型选择T#T#GranularityKey中。
你能解释一下这里到底会发生什么反射调用吗?那么它实际上是类型安全的吗?
发布于 2021-01-26 15:59:52
也许,由于next type Aux[TT <: Granularity] = Test{ type T = TT } -基本上您在这里说有一些Test应该在其中定义了类型别名T。我认为这里的编译器逻辑类似于Scala实现中的Duck Typing。例如,您可以定义type Foo{ def bar(): Unit},然后尝试下一步
class FooImpl {
def bar(): Unit = println("Bar")
}
val foo: Foo = new FooImpl
foo.bar()正如您所看到的,FooImpl不会继承任何东西,但仍然可以为类型Foo赋值,因为它满足具有方法bar的条件,但由于foo.bar()限制或字节码限制- JVM调用将是反射的,这意味着通过Java反射API。但是,这种方法是完全类型安全的。
也许,基于此的想法也认为Test特征中的类型别名T将通过反射API调用。
https://stackoverflow.com/questions/65897427
复制相似问题