类型类解析中的隐式类别

问题描述

我怀疑,

大多数人都知道 Show 示例来介绍类型类。

我发现了此博客帖子https://scalac.io/typeclasses-in-scala/,当我偶然发现一些我不太了解的东西,并希望有人可以帮助澄清它时,我的工作就变得很容易。

我了解该博客文章在谈到隐式类别时所期望的一切:

从类型类的完整定义中获取语法和对象接口

$ref

我们收到以下评论:

我们可能需要重新定义一些默认类型类实例。通过上述实现,如果所有默认实例都导入了作用域,我们将无法实现。编译器的作用域将具有不明确的隐式范围,并将报告错误。

我们可能决定移动show函数和ShowOps隐式类 到另一个对象(例如ops),以允许此类用户 重新定义默认实例行为(使用1类隐式, 有关隐式类别的更多信息)。经过这样的修改, 对象看起来像这样:

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"
}

用法不变,但是现在此类用户只能导入:

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"

}

默认隐式实例不作为1类隐式提供(尽管它们可以作为2类隐式使用),因此可以在使用此类类型类的地方定义我们自己的隐式实例。

我没有得到最后的评论?

解决方法

Show[Int]伴随对象中定义了Show[String]Show的隐式实例,因此,只要使用类型为Show的值,类型类实例就可以使用。但是,它们可以被用户覆盖。这使它们成为2类隐式对象-它们来自隐式范围

另一方面,通过直接导入引入范围的隐式类别1隐式。它们来自本地范围,并且不能被覆盖。因此,直接导入隐式方法与在现场定义它们是相同的-两者都被视为类别1。如果在本地范围内存在多个同一类型的1类隐式值,编译器会抱怨。

本文所说的是,将隐式实现放在伴随对象中,而将“机械”放在ops中。这样一来,您的类型类别的用户就可以导入机器,从而允许他们执行例如42.show,而不必将类型类实例作为类别1值。

我们的用户可以执行以下操作:

import show.Show
import show.Show.ops._

// available from Show as category 2 implicit:
println(42.show) // "int 42"

以及:

import show.Show
import show.Show.ops._

// overriding category 2 implicit with our own category 1 implicit:
implicit val myOwnIntCanShow: Show[Int] = int => s"my own $int"
println(42.show) // prints "my own 42"

但是,如果我们没有ops对象,而只是将所有内容都放在Show对象中,那么只要我们的用户执行import Show._(并且他们需要为了能够执行42.show),它们将收到我们所有的隐式作为类别1值,并且将无法覆盖它们:

import show.Show

// Assuming everything is in `Show` (no `ops`)...
import show.Show._

implicit val myOwnIntCanShow: Show[Int] = int => s"my own $int"

// this line doesn't compile because implicits were brought 
// into scope as category 1 values (via import Show._)
println(42.show)
,

本教程的作者将较高优先级的隐式(来自本地范围)称为 Category-1隐式和较低优先级的隐式(来自隐式范围) Category-2隐式

Where does Scala look for implicits?

https://docs.scala-lang.org/tutorials/FAQ/finding-implicits.html

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...