我有以下代码,我不知道有什么区别:
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"
}
Run Code Online (Sandbox Code Playgroud)
两者都是类型的实现。问题是,何时使用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)
}
Run Code Online (Sandbox Code Playgroud)
您boxPrintable采用类型参数A和类型的值参数Printable[A],因此必须为def。
String是一种特定类型,因此stringPrintable根本不需要任何参数,它只是一个常量,因此可以将其定义为val。
仅此而已。
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |