gpt4 book ai didi

scala - 使用 Seq 自动衍生的 Cats

转载 作者:行者123 更新时间:2023-12-04 12:21:06 25 4
gpt4 key购买 nike

我想为某些类型定义相等性,这些类型可以是使用猫/小猫的其他对象或集合的一部分。我不想为每个其他类定义相等性。
例如:

import cats.Eq

case class Foo(a: Int, bar: Bar)

case class Bar(b: Int)

object BarEq {
implicit val barEq: Eq[Bar] = Eq.instance[Bar] {
(b1, b2) => b1.b +1 == b2.b
}
}
然后测试定义为
import cats.derived.auto.eq._


class BarEqTest extends FlatSpec with cats.tests.StrictCatsEquality {
import BarEq._

"bareq" should {
"work" in {
Foo(1, Bar(1)) should ===(Foo(1, Bar(2)))
Bar(1) should ===(Bar(2))
Some(Foo(1, Bar(1))) should ===(Some(Foo(1, Bar(2))))
}
}
}

这工作正常,但如果我尝试添加以下测试用例
Seq(Foo(1, Bar(1))) should ===(Seq(Foo(1, Bar(2))))
我得到
[Error] types Seq[Foo] and Seq[Foo] do not adhere to the type constraint selected for the === and !== operators; the missing implicit parameter is of type org.scalactic.CanEqual[Seq[Foo],Seq[Foo]]
one error found
自动导出的 eq 如何与 Option 一起使用但不是 Seq ,我怎样才能让它工作?
我尝试添加 import cats.instances.seq._但这也不起作用。

最佳答案

Cats 定义了一个 Eq 的实例为 scala.collection.immutable.Seq , 不适用于通用 scala.collection.Seq (或此外 scala.collection.mutable.Seq)

import scala.collection.immutable.{BitSet, Queue, Seq, SortedMap, SortedSet}

private[kernel] trait EqInstances0 {
implicit def catsKernelEqForSeq[A: Eq]: Eq[Seq[A]] = cats.kernel.instances.seq.catsKernelStdEqForSeq[A]
}
https://github.com/typelevel/cats/blob/main/kernel/src/main/scala/cats/kernel/Eq.scala#L283-L285
从 Scala 2.13.0 scala.Seq 开始是 scala.collection.immutable.Seq .但在 Scala 2.12.x scala.Seqscala.collection.Seq .
https://github.com/scala/scala/releases/tag/v2.13.0
所以在 Scala 2.12 中导入正确的集合类型
import scala.collection.immutable.Seq
Seq(Foo(1, Bar(1))) === Seq(Foo(1, Bar(2))) // true
或定义您自己的 Eq 实例对于必要的收藏
import cats.kernel.instances.StaticMethods

implicit def genericSeqEq[A: Eq]: Eq[collection.Seq[A]] = new Eq[collection.Seq[A]] {
override def eqv(xs: collection.Seq[A], ys: collection.Seq[A]): Boolean =
if (xs eq ys) true
else StaticMethods.iteratorEq(xs.iterator, ys.iterator)
}

Seq(Foo(1, Bar(1))) === Seq(Foo(1, Bar(2))) // true

关于scala - 使用 Seq 自动衍生的 Cats,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69591709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com