创建单一类型对象的列表

Creating a list of single type of objects

我有一个 Animal 特征和一些案例 class 如下

sealed trait Animal

trait Domestic extends Animal
trait Wild extends Animal

case class Dog(id: UUID = UUID.randomUUID()) extends Domestic
case class Lion(id: UUID = UUID.randomUUID()) extends Wild

这是我的 Herd class,它可以包含单一类型动物的列表

case class Herd[T <: Animal](get: T*)

我要创建的是一群单一类型的动物。

val herd1 = Herd(Cat(), Cat())
val herd2 = Herd(Cat(), Lion())

在 Scala 中两者都是有效的,但是如果你看一下 a herd of cats and lions 的意思,它就没有意义了。有没有办法限制 Herd 为单一类型?

尝试引入两个类型参数 AB,然后将它们与通用类型约束相关联 A =:= B

case class Herd[A <: Animal, B](x: A, y: B*)(implicit ev: A =:= B)

Herd(Lion())         // ok
Herd(Lion(), Lion()) // ok
Herd(Cat(), Lion())  // compile-time error

what exactly is =:=

考虑以下带有两个类型参数 AB 的方法,我们旨在传达它们应该相等或至少 A 应该是 [=22] 的子类型=]

scala> def f[A, B](a: A, b: B): B = {
     |   val x: B = a
     |   x
     | }
         val x: B = a
                    ^
On line 2: error: type mismatch;
        found   : a.type (with underlying type A)
        required: B

上述定义中的两个类型参数完全无关,方法体无法影响类型参数的类型推断,因此出错。现在让我们尝试将它们与类型绑定相关联 A <: B

scala> def f[A <: B, B](a: A, b: B): B = {
     |   val x: B = a
     |   x
     | }
def f[A <: B, B](a: A, b: B): B

因此可以编译,但是编译器将始终通过计算给定参数的最小上限来尝试满足类型界限

scala> f(Lion(), Dog())
val res32: Product with Animal with java.io.Serializable = Lion(...)

我们需要更多的东西来解决编译器推断最小上限的倾向,这就是广义类型相等约束发挥作用的地方

scala> def f[A <: B, B](a: A, b: B)(implicit ev: A =:= B): B = {
     |   val x: B = a
     |   x
     | }
def f[A <: B, B](a: A, b: B)(implicit ev: A =:= B): B

scala> f(Lion(), Cat())
        ^
       error: Cannot prove that Lion =:= Product with Animal with java.io.Serializable.

现在编译器仍然必须尝试生成给定参数的最小上限,但是它还必须满足能够为两种类型生成见证 ev 的额外要求 AB 相等。 (注意 witness ev 将由编译器自动实例化,如果可能的话。)

一旦我们有了 witness ev,我们就可以通过它的 apply 方法在类型 AB 之间自由移动,例如,考虑

scala> type A = Lion
type A

scala> type B = Lion
type B

scala> val a: A = Lion()
val a: A = Lion(...)

scala> val ev: =:=[A, B] = implicitly[A =:= B]
val ev: A =:= B = generalized constraint

scala> ev.apply(a)
val res44: B = Lion(...)

请注意 ev.apply(a) 如何键入 B。我们之所以可以这样应用=:=是因为它实际上是一个函数

scala> implicitly[(A =:= B) <:< Function1[A, B]]
val res43: A =:= B <:< A => B = generalized constraint

所以隐式参数列表

(implicit ev: A =:= B)

实际上是在指定隐式转换函数

(implicit ev: A => B)

所以现在编译器能够在需要的地方自动注入隐式转换,所以下面

def f[A <: B, B](a: A, b: B)(implicit ev: A =:= B): B = {
  val x: B = a
  x
}

自动扩展为

def f[A <: B, B](a: A, b: B)(implicit ev: A =:= B): B = {
  val x: B = ev.apply(a)
  x
}

总而言之,就像类型边界一样,广义类型约束是另一种要求编译器在编译时对我们的代码库进行进一步检查的方法。