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

8
假设我有以下内容:
class Bounded[A] {
  type apply[C <: A] = C
}

这段代码可以编译:

implicitly[Bounded[Any]#apply[String] =:= String]

这个失败了:

type Str = Bounded[Any]#apply[String]

使用以下内容:

[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]                           ^

我尝试使用抽象类型替代类型参数,但结果相同。我找到的唯一解决方法是实例化该类型。以下代码可以编译:

val boundedAny = new Bounded[Any]
type Str2 = boundedAny.apply[String]

很不幸,我正在使用幽灵类型进行编程,这些类型通常由于性能原因没有运行时实例。

为什么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
}
1个回答

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>

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

谢谢,这个 bug 给我带来了很多的挫败感。 - Grant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接