Caching implicit resolution

隐身守侯 提交于 2019-12-03 02:52:23

Shapeless provides a cachedImplicit macro with an implementation that's very similar to yours (it uses shadowing to avoid the recursion, and the fact that it's a macro means the usage can be cleaner).

There are some limitations to be aware of, and you may not want to take on a new dependency for this single method, but the implementation is pretty concise, and it's at least a good starting point.

Just for the sake of completeness: the shapeless macro in the accepted answer shadows its own definition in a way I didn't come up with. My particular problem could therefore be solved this way:

implicit val x: String = {
    def x = ???
    implicitly[String]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!