函数定义中返回类型后的大括号

在阅读cats库的Functor源码时,无法理解toFunctorOps函数返回类型后的curl块是做什么的;我的猜测是这个块将作为构造函数的一部分执行?如果是这样,那么,为什么类型TypeClassType与相同的代码定义了两次类型TypeClassType =函子[F]

  trait Ops[F[_], A] extends Serializable {
    type TypeClassType <: Functor[F]
    def self: F[A]
    val typeClassInstance: TypeClassType
    def map[B](f: A => B): F[B] = typeClassInstance.map[A, B](self)(f)
    ...
  }

  trait ToFunctorOps extends Serializable {
    implicit def toFunctorOps[F[_], A](target: F[A])(implicit tc: Functor[F]): Ops[F, A] {
      type TypeClassType = Functor[F]
    } =
      new Ops[F, A] {
        type TypeClassType = Functor[F]
        val self: F[A] = target
        val typeClassInstance: TypeClassType = tc
      }
  }

回答

我无法理解返回类型后的卷曲块是什么......

改进对 trait 的{ type TypeClassType = Functor[F] }类型成员施加了进一步的限制。换句话说,它向编译器提供了有关方法的特定返回类型的更多信息TypeClassTypeOpstoFunctorOps

Ops[F, A] { type TypeClassType = Functor[F] }

请注意,细化块被视为返回类型的一部分,与构造函数无关。

让我们简化类型以更好地说明这个概念,所以考虑

trait Foo {
  type A
  def bar: A
}

val foo: Foo = new Foo { 
  type A = Int 
  def bar: A = ???
}
val x: foo.A = 42 // type mismatch error

请注意变量的静态类型如何foo不包括类型成员A已实例化的特定信息Int。现在让我们使用类型细化向编译器提供此信息

val foo: Foo { type A = Int } = new Foo { 
  type A = Int
  def bar: A = ??? 
}
val x: foo.A = 42 // ok

现在编译器知道类型成员A正是一个Int.

类型类的设计者在何时使用类型成员而不是类型参数方面做出明智的决定,有时甚至在您的情况下两者混合使用。例如 traitFoo可以像这样被参数化

trait Foo[A] {
  def bar: A
}
val foo: Foo[Int] = new Foo[Int] { 
  def bar: Int = ??? 
}

并且编译器将再次获得类型参数A已实例化为的精确信息Int

为什么类型 TypeClassType 被定义了两次

细化类型Foo { type A = Int }是 的较窄的子类型Foo,类似于如何Cat是 的较窄的子类型Animal

implicitly[(Foo { type A = Int }) <:< Foo]
implicitly[Cat <:< Animal]

所以即使右侧的表达式实例A化为Int,左侧的表达式也明确告诉编译器的静态类型foo只是更宽的超类型Foo

val foo: Foo = new Foo { 
  type A = Int 
  def bar: A = ???
}

类似于编译器如何知道zar下面的静态类型只是更广泛的超类型,Animal尽管 RHS 上的表达式指定了Cat

val zar: Animal = new Cat

因此需要“双重”类型规范

val foo: Foo { type A = Int } = new Foo { 
  type A = Int 
  ...
}

相似

val zar: Cat = new Cat

我们可以尝试依靠推理来推断出最具体的类型,但是当我们显式注释类型时,我们必须通过细化提供包括类型成员约束的完整信息。


以上是函数定义中返回类型后的大括号的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>