【发布时间】:2015-05-09 19:44:42
【问题描述】:
在一个播放框架 (Scala) Web 应用程序中,我解析了一些 JSON 以获得递归类型。为了实现这一点,我使用了读者的惰性引用,就像在play's official documentation 上推荐的那样(向下滚动到“递归类型”)。
这可行,但我收到警告:
[info] Compiling 1 Scala source to /path-to-project/target/scala-2.11/classes...
[warn] /path-to-project/app/controllers/JSONFormats.scala:116: Reference to uninitialized value layerTreeNodeFormat
[warn] val folderNodeFormat = Format(folderNodeReads, Json.writes[FolderNode])
[warn] ^
[warn] one warning found
有什么办法可以关闭此警告吗?我查看了 Scala 的 @unchecked,但我不确定如何(如果有的话)在这里应用它。
谢谢!
编辑:以下是代码的相关部分。 JSON 解析器解析地图层的异构树。一些节点(“层”)是叶子,而其他节点(“文件夹”)可以包含层和其他文件夹(因此递归)。在 Scala 方面,有一个抽象基类 LayerTreeNode 和两个具体案例类:LayerNode 和 FolderNode。
object ProjectJSONFormats {
// omitted code...
/** Turns the tuple parsed from JSON into a FolderNode. */
def tupleToFolder( id:String, jsType:String, name:String, children:Seq[LayerTreeNode] ) = FolderNode(id, name, children)
val folderNodeReads: Reads[FolderNode] = (
(JsPath \ "id").read[String] and
(JsPath \ "type").read[String] and
(JsPath \ "title").readNullable[String].map( _.getOrElse("") ) and
(JsPath \ "children").lazyReadNullable(Reads.seq[LayerTreeNode](layerTreeNodeReads)).map( _.getOrElse(Seq[LayerTreeNode]()))
)( tupleToFolder _)
val folderNodeFormat = Format(folderNodeReads, Json.writes[FolderNode])
implicit val layerNodeFormat = Json.format[LayerNode]
val layerTreeNodeReads: Reads[LayerTreeNode] = new Reads[LayerTreeNode] {
override def reads(json: JsValue): JsResult[LayerTreeNode] = {
if ( (json\"type").as[String] == "folder" ) {
folderNodeFormat.reads(json)
} else {
layerNodeFormat.reads(json)
}
}
}
val layerTreeNodeWrites: Writes[LayerTreeNode] = new Writes[LayerTreeNode] {
override def writes(o: LayerTreeNode): JsValue = o match {
case f:FolderNode => folderNodeFormat.writes(f)
case l:LayerNode => layerNodeFormat.writes(l)
}
}
implicit val layerTreeNodeFormat:Format[LayerTreeNode] = Format( layerTreeNodeReads, layerTreeNodeWrites )
}
【问题讨论】:
-
@unchecked不适用于此处,因为它用于忽略类型检查器警告。你确定这个警告没有任何价值吗?初始化顺序可能最终会在这里咬你,但如果没有看到实际代码就很难说。 -
谢谢。正如我所说 - 这是惯用的。它不会咬我,因为我将它作为参数传递给按名称调用的方法 JsPath#lazyReadNullable。 (playframework.com/documentation/2.3.x/api/scala/…)
-
您能否将实际代码添加到您的问题中?
标签: scala playframework