小猫-含糊的进口(再次)

时间:2019-05-29 22:24:30

标签: scala shapeless scala-cats

这个答案https://stackoverflow.com/a/56366311/2682459显示了在使用Kitten时如何使用对象来提供类型类的自定义实现。将相同的原理应用于以下代码虽然不起作用:

package com.xxx.yyy.zzz

import cats._, cats.derived._, cats.implicits._

object Test extends App {

  case class Inner(double: Double)

  case class Outer(inner: Inner, s: String)

  implicit object doubleEq extends Eq[Double] {
    override def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
  }

  implicit val outerEq: Eq[Outer] = {
    import derived.auto.eq._
    derived.semi.eq[Outer]
  }

  implicitly[Eq[Double]]

  val testCC1 = Outer(Inner(1.01d), "BlahBlahBlah")
  val testCC2 = Outer(Inner(1.00d), "BlahBlahBlah")

  println(testCC1 === testCC2)

}

implicitly[Eq[Double]]再次表明我具有含糊的隐式:

Error:(20, 13) ambiguous implicit values:
 both value catsKernelStdOrderForDouble in trait DoubleInstances of type => cats.kernel.Order[Double] with cats.kernel.Hash[Double]
 and object doubleEq in object Test of type com.xxx.yyy.zzz.Test.doubleEq.type
 match expected type cats.Eq[Double]
  implicitly[Eq[Double]]

我该如何解决这个问题?我真的不想不得不挑选我导入的猫隐式对象,因为这不是很容易扩展!

2 个答案:

答案 0 :(得分:2)

更改进口。不要导入cats.instances.double._

import cats._, cats.derived._
import cats.instances.string._ // Outer uses Double and String
import cats.syntax.eq._ // for ===

两者

implicit val doubleEq: Eq[Double] = new Eq[Double] {
  override def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
}

implicit object doubleEq extends Eq[Double] {
  override def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
}

工作。

http://eed3si9n.com/herding-cats/import-guide.html

https://blog.softwaremill.com/9-tips-about-using-cats-in-scala-you-might-want-to-know-e1bafd365f88建议2)

答案 1 :(得分:1)

更多玩-这似乎给了我我想要的东西:

import cats._
import cats.derived._
import cats.syntax.eq._
import derived.auto.eq._

object CustomImplicits extends cats.instances.AllInstances {
  implicit object doubleEq extends Eq[Double] {
    def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
  }
}

object Test extends App {

  case class Inner(double: Double)

  case class Outer(inner: Inner, s: String)

  import CustomImplicits._

  implicitly[Eq[Double]]

  val testCC1 = Outer(Inner(1.01d), "BlahBlahBlah")
  val testCC2 = Outer(Inner(1.00d), "BlahBlahBlah")
  val testCC3= Outer(Inner(2.00d), "BlahBlahBlah")

  println(testCC1 === testCC2) //True
  println(testCC2 === testCC3) //False

}