如何防止在scala代码中使用特定的隐式?
例如,我最近被https://github.com/scala/scala/blob/68bad81726d15d03a843dc476d52cbbaf52fb168/src/library/scala/io/Codec.scala#L76提供的默认Codec占用了。有没有办法确保任何调用implicit codec: Codec的代码永远不会使用fallbackSystemCodec提供的代码?或者,是否可以阻止所有隐式编解码器?
使用scalafix可以做到这一点吗?
发布于 2019-03-30 11:20:51
Scalafix可以使用SemanticTree进行inspect implicit arguments。Here是一个示例解决方案,它定义了一个自定义的scalafix规则。
给定的
import scala.io.Codec
object Hello {
def foo(implicit codec: Codec) = 3
foo
}我们可以定义一个自定义规则
class ExcludedImplicitsRule(config: ExcludedImplicitsRuleConfig)
extends SemanticRule("ExcludedImplicitsRule") {
...
override def fix(implicit doc: SemanticDocument): Patch = {
doc.tree.collect {
case term: Term if term.synthetic.isDefined => // TODO: Use ApplyTree(func, args)
val struct = term.synthetic.structure
val isImplicit = struct.contains("implicit")
val excludedImplicit = config.blacklist.find(struct.contains)
if (isImplicit && excludedImplicit.isDefined)
Patch.lint(ExcludedImplicitsDiagnostic(term, excludedImplicit.getOrElse(config.blacklist.mkString(","))))
else
Patch.empty
}.asPatch
}
}和相应的.scalafix.conf
rule = ExcludedImplicitsRule
ExcludedImplicitsRuleConfig.blacklist = [
fallbackSystemCodec
]应启用sbt scalafix以引发诊断
[error] /Users/mario/IdeaProjects/scalafix-exclude-implicits/example-project/scalafix-exclude-implicits-example/src/main/scala/example/Hello.scala:7:3: error: [ExcludedImplicitsRule] Attempting to pass excluded implicit fallbackSystemCodec to foo'
[error] foo
[error] ^^^
[error] (Compile / scalafix) scalafix.sbt.ScalafixFailed: LinterError请注意println(term.synthetic.structure)的输出
Some(ApplyTree(
OriginalTree(Term.Name("foo")),
List(
IdTree(SymbolInformation(scala/io/LowPriorityCodecImplicits#fallbackSystemCodec. => implicit lazy val method fallbackSystemCodec: Codec))
)
))显然,上面的解决方案不是很有效,因为它搜索字符串,但是它应该给出一些方向。也许在ApplyTree(func, args)上匹配会更好。
scalafix-exclude-implicits-example展示了如何配置项目以使用ExcludedImplicitsRule。
发布于 2019-04-03 00:01:03
您可以通过完全使用新类型来完成此操作;这样,没有人能够在您的依赖项中重写它。这基本上就是我在create an ambiguous low priority implicit上发布的答案
但是,如果您不能更改类型,这可能并不实用。
https://stackoverflow.com/questions/50336960
复制相似问题