多么"无形".缓存"工作?



运行以下代码

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的计算次数与调用次数一样多。但是,如果您通过val更改隐式def,您将有一个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

相关内容

最新更新