Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala “shapeless.Cached”是如何工作的?_Scala_Implicit_Shapeless - Fatal编程技术网

Scala “shapeless.Cached”是如何工作的?

Scala “shapeless.Cached”是如何工作的?,scala,implicit,shapeless,Scala,Implicit,Shapeless,运行以下代码 导入无形状_ 最后一个案例类Foo(s:String){println(“HELLO”)} 对象TestApp扩展应用程序{ 隐式定义foo(隐式s:String):foo=foo(s) 隐式val s:String=“123” 隐式[Foo] 隐式[Foo] val f1=隐式[缓存的[Foo]]。值 val f2=隐式[缓存的[Foo]].值 println(f1等式f2) } 我假设它在屏幕上显示3个“HELLO”,比较结果为true 相反,这是我得到的 你好 你好 你好

运行以下代码

导入无形状_
最后一个案例类Foo(s:String){println(“HELLO”)}
对象TestApp扩展应用程序{
隐式定义foo(隐式s:String):foo=foo(s)
隐式val s:String=“123”
隐式[Foo]
隐式[Foo]
val f1=隐式[缓存的[Foo]]。值
val f2=隐式[缓存的[Foo]].值
println(f1等式f2)
}
我假设它在屏幕上显示3个“HELLO”,比较结果为
true

相反,这是我得到的

你好 你好 你好 你好 假的
我对使用缓存的
方法的理解是否错误?

def
的计算次数与调用次数相同。但是如果您通过
val
更改隐式
def
,您将有一个
HELLO
true

非缓存和缓存的隐式
val
s之间的差异可以如下所示(它是用scaladoc编写的):


谢谢,现在我明白了创建
缓存的实际目的。你知道是否有一种方法可以缓存基于
def
的隐式吗?
def-foo(隐式s:String):foo=foo(s)
隐式val-foo1:foo=foo
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