无法在 Scala Worksheet 中的伴随对象中找到隐式值

Could not find implicit value inside companion object in Scala Worksheet

我正在尝试在 IntelliJ Scala Worksheet 中创建一个类型 class。所以我从这样的特征开始

trait Show[A] {
  def show(a : A) : String
}

并创建了一个伴生对象

object Show {

  def show[A](a: A)(implicit sh: Show[A]) = sh.show(a)

  implicit val intCanShow: Show[Int] =
    new Show[Int] {
      def show(int: Int): String = s"int $int"
    }

}

当我尝试时

println(Show.show(20))

我收到这个错误。

Error:(50, 26) could not find implicit value for parameter sh: Show[Int]
println(Show.show(20))

但是当我从对象 Show 中取出 intCanShow 时,它工作正常。为什么 scala 不能访问对象内部的隐式?

隐式解析会尝试伴随对象,因此您的代码看起来没问题。然而,要成为 companion 对象,它必须满足以下两个 requirements

  1. 伴随对象是与 class 或特征同名的对象,并且
  2. 相同的源文件 中定义为关联的 class 或特征。

以下警告表示不满足第二个要求:

defined object Show
warning: previously defined trait Show is not a companion to object Show.
Companions must be defined together; you may wish to use :paste mode for this.

为了满足第二个要求,我们必须在 Scala Worksheet 中使用 Plain 评估模型,或在 Scala REPL 中使用 :paste 模式。

Scala Worksheet Plain 评估模型

要在 IntelliJ Scala Worksheet 中定义伴生对象,请将 Run type 更改为 Plain,就像这样

  1. Show Worksheet Settings
  2. Select 选项卡 Settings for *.sc
  3. Run typeREPL 更改为 Plain

Scala REPL 粘贴模式

按照@jwvh的建议,确保输入paste mode

If a class or object has a companion, both must be defined in the same file. To define companions in the REPL, either define them on the same line or enter :paste mode.

如图所示

当 运行 作为 scala 脚本时,您的示例似乎按预期工作。
在名为 test.sh 并标记为可执行文件

的文件中包含以下内容
#!/usr/bin/env scala
trait Show[A] {
  def show(a : A) : String
}
object Show {
  def show[A](a: A)(implicit sh: Show[A]) = sh.show(a)

  implicit val intCanShow: Show[Int] =
    new Show[Int] {
      def show(int: Int): String = s"int $int"
    }
}

println(Show.show(20))

我观察

bash-3.2$ ./test.sh
int 20