Scala 正在解析具有类型成员的类型的“清单”

Scala 正在解析具有类型成员的类型的“清单”,scala,type-members,Scala,Type Members,我无法为具有类型成员的类型解析scala.reflect.Manifest 比如说, import scala.reflect.Manifest trait Foo { type T } trait Bar[T] object Main extends App { val barM: Manifest[Bar[Int]] = implicitly[Manifest[Bar[Int]]] val fooM: Manifest[Foo{type T = Int}] =

我无法为具有类型成员的类型解析
scala.reflect.Manifest

比如说,

import scala.reflect.Manifest

trait Foo {
  type T
}

trait Bar[T]

object Main extends App {

  val barM: Manifest[Bar[Int]] =
    implicitly[Manifest[Bar[Int]]]

  val fooM: Manifest[Foo{type T = Int}] =
    implicitly[Manifest[Foo{type T = Int}]]

}
上面的代码未编译,出现以下错误

Foo.scala:15: error: type mismatch;
 found   : scala.reflect.Manifest[Foo]
 required: scala.reflect.Manifest[Foo{type T = Int}]
Note: Foo >: Foo{type T = Int}, but trait Manifest is invariant in type T.
You may wish to investigate a wildcard type such as `_ >: Foo{type T = Int}`. (SLS 3.2.10)
    implicitly[Manifest[Foo{type T = Int}]]
              ^
one error found
但是
barM
声明工作得很好

我知道类型成员并不完全是类型参数,但我肯定不了解所有的细节


如何为具有具体类型成员的类型解析
清单

清单不支持结构类型。(
Manifest
结构类型)标记为“不会修复”,建议您改用
TypeTag
<代码>清单也可能很快被弃用

scala> import scala.reflect.runtime.universe.TypeTag
import scala.reflect.runtime.universe.TypeTag

scala> implicitly[TypeTag[Foo { type T = Int} ]]
res18: reflect.runtime.universe.TypeTag[Foo{type T = Int}] = TypeTag[Foo{type T = Int}]
您也可以使用类型别名来解决这个问题,但是如果没有用例,很难判断

scala> type FooAux[T] = Foo { type T }
defined type alias FooAux

// Compiles, but is it useful?
scala> implicitly[Manifest[FooAux[Int]]]
res19: scala.reflect.Manifest[FooAux[Int]] = Foo

我原以为你的答案是正确的,但现在我不确定。这不是一种结构类型。虽然语法类似,但结构类型会发出反射调用以验证某些内容是否正确,而这只是普通的旧类型成员,没有反射调用。我已经尝试了类型别名解决方案。遗憾的是,它不起作用,因为编译器仍然对类型成员的差异感到不安。看起来它可能与此有关。