【问题标题】:Type pattern matching and inference error in Scala 3Scala 3 中的类型模式匹配和推理错误
【发布时间】:2021-08-24 16:15:52
【问题描述】:

我正在使用 Scala 3 中的类型类,遇到了一个我无法解释的编译错误。

考虑以下代码:

trait Transformation[Input, Output <: Tuple]:
  def apply(x: Input): Output


trait ListOfTransformations[T[_, _] <: Transformation[_, _], Input <: Tuple, Output <: Tuple] extends Transformation[Input, Output]

object ListOfTransformations:
  given empty[T[_, _] <: Transformation[_, _]]: ListOfTransformations[T, EmptyTuple, EmptyTuple] with
    def apply(t: EmptyTuple): EmptyTuple = t

  given nonEmpty[T[_, _] <: Transformation[_, _], Head, Tail <: Tuple, HeadOutput <: Tuple, TailOutput <: Tuple](
    using
    ht: T[Head, HeadOutput],
    tt: ListOfTransformations[T, Tail, TailOutput]
  ): Transformation[Head *: Tail, Tuple.Concat[HeadOutput, TailOutput]] with
    def apply(x: Head *: Tail): Tuple.Concat[HeadOutput, TailOutput] = ht(x.head) ++ tt(x.tail)

我明白了:

Found:    Tuple.Head[Head² *: Tail]
Required: nonEmpty.this.ht.Input

where:    Head  is a type in object Tuple which is an alias of [X <: NonEmptyTuple] =>> 
  X match {
    case [x, _ <: Tuple] =>> scala.runtime.MatchCase[x *: _, x]
  }
          Head² is a type in class nonEmpty
          Tail  is a type in class nonEmpty with bounds <: Tuple

我错过了什么?

【问题讨论】:

  • Head 既是nonEmpty 的类型参数,也是Tuple 对象中定义的类型(参见此处:dotty.epfl.ch/api/scala/Tuple$.html#Head-0)。也许编译器认为您在某处引用 Tuple.Head 而不是类型参数,反之亦然?您可以尝试将您的类型参数重命名为其他名称吗?
  • @marstran 我将它重命名为H 并且错误消息发生了变化(奇怪),但它并没有消失:找到:Tuple.Head[H *: Tail] 必需:nonEmpty.this。 ht.Input 其中:Tail 是类 nonEmpty 中的类型,边界为 <: tuple>
  • 错误已经改变的事实让我更加困惑,因为在任何地方都没有导入 Tuple.Head,所以不应该与它混淆
  • 这是示例顺便说一句:scastie.scala-lang.org/0qRSPun5QIe9vsK70EVYuw
  • Tail 也是Tuple 中的一个类型。尝试重命名那个。

标签: scala typeclass implicit type-level-computation scala-3


【解决方案1】:

当使用带边界的类型构造函数作为类型参数时,请确保使用实际参数而不是通配符。使用 T[a, b] &lt;: Transformation[a, b] 而不是 T[_, _] &lt;: Transformation[_, _] 可以编译 (Scastie)。前者采用类型构造函数,当给定两种类型时,该类型为Transformation[a, b] 的子类型,用于某些我们不知道的ab。通过不使用通配符(并忽略 T 的实际参数),您可以让编译器准确地知道 T[a, b] 是什么子类型。

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 2020-08-09
    • 2015-04-30
    • 1970-01-01
    • 2018-01-03
    • 2013-03-17
    • 1970-01-01
    相关资源
    最近更新 更多