问题描述
考虑以下示例:
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
中发生的一些反射调用的想法信号。
你能解释一下这里会发生什么反射调用吗?那么它实际上是类型安全的吗?
解决方法
也许,因为下一个 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
的条件,但由于 JVM 限制或字节码限制 - foo.bar()
调用将是反射的,这意味着通过 Java 反射 API。但是,尽管这种方法是完全类型安全的。
也许,Idea 也因此认为 T
trait 中的类型别名 Test
将通过反射 API 调用。