【发布时间】:2021-01-07 15:04:30
【问题描述】:
我怀疑,
大多数人都知道Show示例来介绍类型类。
我发现了这篇博文https://scalac.io/typeclasses-in-scala/,当我偶然发现一些我不太理解的东西并希望有人可以帮助澄清它时,我很容易就解决了。
我理解博文中关于隐式类别的所有内容:
从带有语法和对象接口的类型类完整定义
trait Show[A] {
def show(a: A): String
}
object Show {
def apply[A](implicit sh: Show[A]): Show[A] = sh
//needed only if we want to support notation: show(...)
def show[A: Show](a: A) = Show[A].show(a)
implicit class ShowOps[A: Show](a: A) {
def show = Show[A].show(a)
}
//type class instances
implicit val intCanShow: Show[Int] =
int => s"int $int"
implicit val stringCanShow: Show[String] =
str => s"string $str"
}
我们得到以下评论:
我们可能会遇到需要重新定义一些默认类型类实例。使用上面的实现,如果所有默认实例都被导入作用域,我们就无法实现。编译器会在范围内有模糊的隐式,并会报告错误。
我们可能决定移动 show 函数和 ShowOps 隐式类 到另一个对象(比如说操作)以允许此类用户 重新定义默认实例行为(使用类别 1 隐式, 更多关于隐含类别的信息)。经过这样的修改,秀 对象看起来像这样:
object Show {
def apply[A](implicit sh: Show[A]): Show[A] = sh
object ops {
def show[A: Show](a: A) = Show[A].show(a)
implicit class ShowOps[A: Show](a: A) {
def show = Show[A].show(a)
}
}
implicit val intCanShow: Show[Int] =
int => s"int $int"
implicit val stringCanShow: Show[String] =
str => s"string $str"
}
用法不变,但现在该类型类的用户只能导入:
import show.Show
import show.Show.ops._
默认隐式实例不作为第 1 类隐式引入(尽管它们可作为第 2 类隐式使用),因此可以在使用此类类型类的地方定义我们自己的隐式实例。
我没有收到最后一条评论?
【问题讨论】:
标签: scala functional-programming typeclass implicit purely-functional