代码之家  ›  专栏  ›  技术社区  ›  samba

scala-使用map函数连接jvalue

  •  1
  • samba  · 技术社区  · 6 年前

    我最近开始使用scala,可能遗漏了一些关于map函数的内容。我理解它返回一个新的值,这个值是应用给定函数产生的。

    例如,我有一个jValue数组,希望将数组中的每个值与另一个jValue连接起来,或者像下面的示例一样将其转换为字符串。

    val salesArray = salesJValue.asInstanceOf[JArray]
    val storesWithSales = salesArray.map(sale => compact(render(sale)) //Type mismatch here
    val storesWithSales = salesArray.map(sale => compact(render(sale) + compact(render(anotherJvalue))) //Type mismatch here
    

    正如我看到的,类型不匹配,因为实际值是字符串,而预期值是jValue。即使我这样做了 compact(render(sale).asInstanceOf[JValue] 不允许将字符串强制转换为jValue。是否可以从映射函数返回不同的类型?如何处理数组值以将它们中的每一个转换为另一个类型?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Joe K    6 年前

    查看的类型签名 map 方法:

    def map(f: JValue => JValue): JValue
    

    所以有点不同 地图 方法,其中必须指定返回类型为 JValue . 这是因为 JArray 表示一个反序列化的JSON树,不能只保存任意对象或数据 J值 S.

    如果要处理 JARSART ,呼叫 .children 先上吧。这给了你一个 List[JValue] 它有一个更一般的 地图 方法自 List S可以容纳任何类型。其类型签名为:

    def map[B](f: A => B): List[B]
    

    所以你可以这样做:

    val storesWithSales = salesArray.children.map(sale => compact(render(sale)))
    
    推荐文章