1

运行以下代码

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

4

1 回答 1

3

def被评估的次数与调用次数一样多。但是如果你改变隐含def的,val你将拥有一个HELLOand true

非缓存和缓存隐式vals 之间的区别可以如下所示(它是用 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
于 2018-08-23T21:08:52.227 回答