如何关闭 Scala 中因方法重载而导致代码无法编译的特定隐式?

2024-05-17

我正忙着尝试自己回答这个问题:Scala Play 2.4.x 通过 anorm (MySQL) 处理扩展字符到 Java Mail https://stackoverflow.com/questions/31417718/scala-play-2-4-x-handling-extended-characters-through-anorm-mysql-to-java-mail

我遇到了这个可能的解决方案:https://objectpartners.com/2013/04/24/html-encoding-utf-8-characters/ https://objectpartners.com/2013/04/24/html-encoding-utf-8-characters/

所以我决定用 Scala 重写示例:

  def htmlEncode(input: String) = htmlEncode_sb(input).toString

  def htmlEncode_sb(input: String, stringBuilder: StringBuilder = new StringBuilder()) = {
    for ((c, i) <- input.zipWithIndex) {
      if (CharUtils.isAscii(c)) {
        // Encode common HTML equivalent characters
        stringBuilder.append(StringEscapeUtils.escapeHtml4(c.toString()))
      } else {
        // Why isn't this done in escapeHtml4()?
        stringBuilder.append(String.format("&#x%x;": String, Character.codePointAt(input, i)))
      }
    }
    stringBuilder
  }
}

仅供参考:我倾向于将大多数在字符串上工作的东西重写到包装的 StringBuilder 调用中,以防我已经使用另一个 StringBuilder 构建某些东西,在这种情况下,我可以将该 StringBuilder 作为参数传递 - 如果没有,则可以正常工作通过调用第一个函数来字符串。

你可能会认为这一切都很好,但是 Scala 编译器有这样的说法:

[info] Compiling 1 Scala source to /SomeOne/SomePath/SomeProject/target/scala-2.11/classes...
[error] /SomeOne/SomePath/SomeProject/TKEmailAgent.scala:278: overloaded method value format with alternatives:
[error]   (x$1: java.util.Locale,x$2: String,x$3: Object*)String <and>
[error]   (x$1: String,x$2: Object*)String
[error]  cannot be applied to (String, Int)
[error]         stringBuilder.append(String.format("&#x%x;": String, Character.codePointAt(input, i)))
[error]                                     ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

请注意,我什至尝试“声明”第一个参数需要是一个字符串:

stringBuilder.append(String.format("&#x%x;": String, Character.codePointAt(input, i)))

然而编译器并没有接受带有 java.util.Locale 的重载方法可以解决问题的提示。

我将代码移动到一个不太混乱的类中,认为这可能是一个导入,但没有这样的运气。

所以问题是如何禁用不是自己选择的隐式?

OR

如何满足编译器了解您真正想要什么的需要?


显然这可以编译:

    stringBuilder.append(String.format("&#x%x;": String, Character.codePointAt(input, i).toString))

然而我相信,如果 toString 首先掌握了东西,这可能会首先破坏调用 format 的整个目的。

所以我原来的问题仍然存在......

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何关闭 Scala 中因方法重载而导致代码无法编译的特定隐式? 的相关文章

随机推荐