Scala:使用类型参数或抽象类型作为类型边界

Gra*_*ant 8 types scala type-bounds phantom-types

假设我有:

class Bounded[A] {
  type apply[C <: A] = C
}
Run Code Online (Sandbox Code Playgroud)

这编译:

implicitly[Bounded[Any]#apply[String] =:= String]
Run Code Online (Sandbox Code Playgroud)

这失败了:

type Str = Bounded[Any]#apply[String]
Run Code Online (Sandbox Code Playgroud)

...有:

[error] /home/grant/Workspace/scunits/test/src/main/scala/Box.scala:37: type arguments[String] do not conform to type apply's type parameter bounds [C <: A]
[error]   type Str = Bounded[Any]#apply[String]
[error]                           ^
Run Code Online (Sandbox Code Playgroud)

我尝试使用抽象类型而不是类型参数,结果相同.我发现的唯一解决方法是实例化类型.这编译:

val boundedAny = new Bounded[Any]
type Str2 = boundedAny.apply[String]
Run Code Online (Sandbox Code Playgroud)

不幸的是,我正在使用没有运行时实例的幻像类型,通常是出于性能原因.

为什么Scala会在这里产生编译错误?有更好的解决方法吗?

谢谢你的帮助.

更新:除了下面的解决方法,我需要一种方法来覆盖具有抽象类型边界的类型.我是这样做的:

object Test {
  class AbstractBounded[A] {
    type apply[C <: A] <: A
    class Workaround[C <: A] {
      type go = apply[C]
    }
  }
  class Bounded[A] extends AbstractBounded[A] {
    type apply[C <: A] = C
  }

  type Str = Bounded[Any]#Workaround[String]#go
}
Run Code Online (Sandbox Code Playgroud)

dk1*_*k14 1

怎么样:

scala> class Bounded[A] { class i[C <: A]{ type apply = C}}
defined class Bounded

scala> type TTT = Bounded[Any]#i[String]#apply
defined type alias TTT

scala> implicitly[TTT =:= String]
res4: =:=[TTT,String] = <function1>
Run Code Online (Sandbox Code Playgroud)

Scala 在将参数绑定到类型别名之前忘记查找泛型(或另一个“抽象”类型)。鉴于 =:= 工作正常 - 对我来说似乎是一个错误。也许隐式正在另一个编译级别上或在此检查之前进行解析。