`shapeless.Cached` 是如何工作的?

How `shapeless.Cached` works?

运行以下代码

import shapeless._

final case class Foo(s: String) { println("HELLO") }

object TestApp extends App {
  implicit def foo(implicit s: String): Foo = Foo(s)

  implicit val s : String = "123"

  implicitly[Foo]

  implicitly[Foo]

  val f1 = implicitly[Cached[Foo]].value
  val f2 = implicitly[Cached[Foo]].value
  println(f1 eq f2)
}

我假设它在屏幕上显示 3 "HELLO",比较结果是 true

相反,这是我得到的,

HELLO
HELLO
HELLO
HELLO
false

我对Cached的使用方式理解有误吗?

def 的计算次数与调用次数一样多。但是,如果您将隐式 def 更改为 val,您将拥有一个 HELLOtrue.

非缓存和缓存隐式val的区别如下(用scaladoc写的):

trait TC[T] {
  def msg: String
}

object First {
  implicit val tc: TC[Int] = new TC[Int] {
    val msg = "first"
  }

  def print() = println(implicitly[TC[Int]].msg)

  def printCached() = println(Cached.implicitly[TC[Int]].msg)
}

object Second {
  implicit val tc: TC[Int] = new TC[Int] {
    val msg = "second"
  }

  def print() = println(implicitly[TC[Int]].msg)

  def printCached() = println(Cached.implicitly[TC[Int]].msg)
}

First.print()//first
Second.print()//second
First.printCached()//first
Second.printCached()//first