我有以下代码,我无法弄清楚,有什么区别:
implicit def BoxPrintable[A](implicit p: Printable[A]) = p.contramap[Box[A]](_.value) implicit val stringPrintable: Printable[String] = new Printable[String] { def format(value: String): String = "Foo " |+| value |+| " Too" }
两者都是类型的实现.问题是,何时使用def以及何时使用val?
整个代码:
package com.sweetsoft import cats.instances.string._ import cats.Syntax.semigroup._ import cats.Contravariant import cats.Show import cats.instances.string._ final case class Box[A](value: A) trait Printable[A] { self => def format(value: A): String def contramap[B](func: B => A): Printable[B] = new Printable[B] { override def format(value: B): String = self.format(func(value)) } } object Main { val showString = Show[String] implicit def BoxPrintable[A](implicit p: Printable[A]) = p.contramap[Box[A]](_.value) implicit val stringPrintable: Printable[String] = new Printable[String] { def format(value: String): String = "Foo " |+| value |+| " Too" } implicit val booleanPrintable: Printable[Boolean] = new Printable[Boolean] { def format(value: Boolean): String = if (value) "yes" else "no" } def main(args: Array[String]): Unit = { println(format("Hello")) //println(format(Box("hello world"))) } def format[A](value: A)(implicit p: Printable[A]): String = p.format(value) }
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。