Json.obj Scala,字符串连接:编译错误



我正在尝试在 Scala 中执行下一个操作,我正在使用 play2:

val str = "another"
val r = Json.obj("error_type" -> "invalid_request_error",
"validation_errors" -> (Json.obj(
"code" -> "this mode " + str + " does not exist",
"param" -> "mode"
)))

但它给了我错误:

Type mismatch, expected: (String, Json.JsValueWrapper), actual: String

但如果我这样做:

val r = Json.obj("error_type" -> "invalid_request_error",
"validation_errors" -> (Json.obj(
("this mode ".+(str)).+(" does not exist"),
"param" -> "mode"
))))

它编译并工作...

如何以 str1 + str2 + str3 的形式编写它更具可读性?这里的顺序/优先级如何相关?在我的回答中,我不明白为什么 (( 既不需要评论。是否有其他类似的情况需要括号?

ps:我不确定在 Java 中是否是同一个问题

这很容易通过查看运算符优先级来解释。

从语言引用 http://scala-lang.org/files/archive/spec/2.11/06-expressions.html#infix-operations,我们可以看到运算符+->具有相同的优先级。这是因为,通常,确定其优先级的是运算符的第一个字符。在我们的例子中,第一个字符是+-,它们都具有相同的优先级。

因此,编写"code" -> "this mode " + str + " does not exist"与编写相同:

"code"
.->("this mode ")
.+(str)
.+(" does not exist")

这与编译器告诉您的内容一致:

  • 第一个运算的结果类型("code" -> "this mode "(是(String, String),相当于Tuple2[String, String]
  • (String, String) + String触发元组上的隐式toString()转换,因此生成的类型为String

您似乎已经找到了以更易读的方式格式化它的更好方法。

至于其他需要括号的情况,显而易见的答案是,一旦您不想要运算符优先级会给您带来什么行为,您就需要它们。因此,我强烈建议阅读上面链接的规范的第 6.12 章!

终于可以做到了,但我不知道原因,我有人知道,请告诉我:

我用 (( 对字符串感到悲伤,它编译并像魅力一样工作:

"code" -> ("payment mode " + another + " does not exist"), ...

总而言之,它将是:

Json.obj("error_type" -> "invalid_request_error",
"validation_errors" -> (Json.obj(
"code" -> ("payment mode " + another + " does not exist"),
"param" -> "payment_mode"
))))

您可以在<code>String</code><code>Seq[String]</code>映射中创建错误消息,然后将其转换为 Json。我认为这将是最好的方法。

最新更新