0

我试图通过 Play Combinators 将 JSONObject 实例映射到实际实例中。我能够使反序列化正常工作。问题是关于 map() 如何在 Option[JSONObject] 上工作的行为。

选项1:

jsonVal: Option[JSONObject] = getAsJson(input)
jsonVal.map(JSONUtil.fromJsonString(_.toString(), Blah.jsonReads))

不起作用,由于 _ 未正确解析而无法编译。编译器在对象上找不到 toString()。

选项2:

jsonVal: Option[JSONObject] = getAsJson(input)
jsonVal.map(_.toString()).map(JSONUtil.fromJsonString(_, Blah.jsonReads))

工作!有人可以告诉我为什么在作为函数参数的一部分进行转换时不传播默认变量的类型吗?

4

1 回答 1

3

这不是 的行为map,而是 的行为_。它只是普通函数表达式的快捷方式(在这种情况下)。在第一种情况下,您有

jsonVal.map(JSONUtil.fromJsonString(x => x.toString(), Blah.jsonReads))

这显然行不通,需要写完整版

jsonVal.map(x => JSONUtil.fromJsonString(x.toString(), Blah.jsonReads))
于 2015-09-20T22:50:31.227 回答