如何使用解码功能?

How to use the decode function?

我试图理解 imap functor 并具有以下代码:

trait Codec[A] {

  def encode(value: A): String

  def decode(value: String): A

  def imap[B](dec: A => B, enc: B => A): Codec[B] = {
    val self = this
    new Codec[B] {
      override def encode(value: B): String =
        self.encode(enc(value))

      override def decode(value: String): B =
        dec(self.decode(value))
    }
  }

}

object Codec {

  implicit val stringCodec: Codec[String] =
    new Codec[String] {
      override def encode(value: String): String = value
      override def decode(value: String): String = value
    }

  implicit val intCodec: Codec[Int] =
    stringCodec.imap(_.toInt, _.toString)

  implicit val booleanCodec: Codec[Boolean] =
    stringCodec.imap(_.toBoolean, _.toString)

  implicit val doubleCodec: Codec[Double] =
    stringCodec.imap(_.toDouble, _.toString)

  def encode[A](value: A)(implicit c: Codec[A]): String =
    c.encode(value)

  def decode[A](value: String)(implicit c: Codec[A]): A =
    c.decode(value)

}

例如,将双精度转换为字符串有效:

  def main(args: Array[String]): Unit = {
   println(Codec.encode(34.343))
  }

但是从 String 到 double:

  def main(args: Array[String]): Unit = {
   println(Codec.decode("34.343"))
  } 

我收到错误消息:

Error:(44, 24) ambiguous implicit values:
 both value stringCodec in object Codec of type => io.khinkali.Codec[String]
 and value intCodec in object Codec of type => io.khinkali.Codec[Int]
 match expected type io.khinkali.Codec[A]
   println(Codec.decode("34.343"))
Error:(44, 24) could not find implicit value for parameter c: io.khinkali.Codec[A]
   println(Codec.decode("34.343"))
Error:(44, 24) not enough arguments for method decode: (implicit c: io.khinkali.Codec[A])A.
Unspecified value parameter c.
   println(Codec.decode("34.343"))

我忘记了什么?

您忘记为 decode 操作指定类型:

Codec.decode[Double]("34.343")

范围内有两个隐式编解码器:Codec[Int]Codec[Double]。编译器如何知道您要使用哪一个?

decode 函数有多个选项(隐式)。如果指定类型参数,那么编译器将能够选择正确的参数:Codec.decode[Double]("34.343").