简体   繁体   English

使用 uJson 库理解这个可变递归 Function

[英]Understanding this Mutable Recursive Function using the uJson library

I am trying to implement an insert function using the ujson library :我正在尝试使用 ujson 实现插入 function :

Here is my attempt:这是我的尝试:

import ujson.{Obj, Value}
import upickle.default._

object Example extends App {
  def r = transform(
    List(Map(
      "a" -> Map("b" -> Obj("c" -> List(1,2,3), "d" -> List(2,4,6))), 
      "e" -> Map("f" -> Obj("g" -> List(1,2,3)))))
  ).to(Value)

  def insert(j: ujson.Value, k: String, v: ujson.Value): Unit = j match {
    case a: ujson.Arr => a.arr.foreach(e => insert(e, k, v))
    case o: ujson.Obj =>
    if (o.obj.keySet contains k)  o.obj(k) = v
    else o.obj.values.foreach(e => insert(e, k, v))
    case _ => Nil
  }

  println(r)
  insert(r, "b", transform(None).to(Value))
  println(r)
}

However, this gives me output that is unchanged:但是,这给了我不变的 output:

[{"a":{"b":{"c":[1,2,3],"d":[2,4,6]}},"e":{"f":{"g":[1,2,3]}}}]
[{"a":{"b":{"c":[1,2,3],"d":[2,4,6]}},"e":{"f":{"g":[1,2,3]}}}]

Given that the Value type is mutable, why does this not mutate and update the key, k, with value v for json value object r?鉴于 Value 类型是可变的,为什么这不会改变和更新键 k,其值为 json 值 object r?

You are creating Value anew every time you call r so, every changes you would make to it, are dismissed.每次调用r时,您都在重新创造Value ,因此,您对其所做的每一次更改都会被取消。

You create one copy when you call println(r) .当您调用println(r)时,您会创建一份副本。

Then you create a separate copy with insert(r, "b", transform(None).to(Value)) , mutate it and dismiss.然后,您使用insert(r, "b", transform(None).to(Value))创建一个单独的副本,对其进行变异并关闭。

Then you are creating third copy with another println(r) .然后,您将使用另一个println(r)创建第三个副本。

If you want to refer to the same object use val instead of def .如果你想引用相同的 object 使用val而不是def

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM