小猫-进口不明确

时间:2019-05-29 17:38:34

标签: scala shapeless scala-cats

我几乎完全从此处的“衍生节目”示例中获取了以下代码:https://github.com/milessabin/kittens

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

object Test extends App {

  case class Address(street: String, city: String, state: String)

  case class ContactInfo(phoneNumber: String, address: Address)

  case class People(name: String, age: Double,  contactInfo: ContactInfo)

  val mike = People("Mike", 1.23,  ContactInfo("202-295-3928", Address("1 Main ST", "Chicago", "IL")))

  implicit val addressShow: Show[Address] = new Show[Address] {
    def show(a: Address) = s"${a.street}, ${a.city}, ${a.state}"
  }

//  I would like to use a custom version of Show for Doubles...
//  implicit val doubleShow: Show[Double] = new Show[Double] {
//    def show(d: Double) = s"Custom Double Show: $d"
//  }

  implicit val peopleShow: Show[People] = {
    import auto.show._
    semi.show
  }

  println(mike.show)

}

我希望能够使用Show [Double]的自定义版本(我不是真的,但这是一个很好的最小示例,它说明了我实际上遇到的问题)

如果我取消对doubleShow的注释,则会出现以下错误:

Error:(25, 10) ambiguous implicit values:
 both value emptyProductDerivedShow in trait MkShowDerivation of type => cats.derived.MkShow[shapeless.HNil]
 and method emptyCoproductDerivedShow in trait MkShowDerivation of type => cats.derived.MkShow[shapeless.CNil]
 match expected type cats.derived.MkShow[A]
    semi.show

我该如何工作?我本来希望我在本地定义的隐式方法能胜过从猫中导入的任何东西...

1 个答案:

答案 0 :(得分:2)

尝试使用隐式对象而不是隐式val

implicit object doubleShow extends Show[Double] {
  def show(d: Double) = s"Custom Double Show: $d"
}

或使用隐式val并更改导入(不要import cats.instances.double._

import cats._, cats.derived._
import cats.syntax.show._
import cats.instances.string._ // People uses String and Double

implicit val doubleShow: Show[Double] = new Show[Double] {
  def show(d: Double) = s"Custom Double Show: $d"
}