我最近开始使用Scala,并且可能缺少有关map函数的某些信息。我知道,它会返回通过应用给定函数得到的新值。
例如,我有一个JValues数组,想要将该数组中的每个值与另一个JValue连接起来,或者只是将其转换为String,如下例所示。
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
如我所见,存在类型不匹配的情况,因为实际值是String,预期值为JValue。即使我compact(render(sale).asInstanceOf[JValue]
也不允许将字符串强制转换为JValue。是否可以从地图函数返回其他类型?我如何处理数组值以将每个数组值转换为另一种类型?
答案 0 :(得分:3)
看看map
方法的类型签名:
def map(f: JValue => JValue): JValue
因此,它与其他map
方法有点不同,因为您必须指定返回类型为JValue
的函数。这是因为JArray
专门表示反序列化的JSON树,并且不能仅包含JValue
来保存任意对象或数据。
如果要处理JArray
的每个值,请先对其调用.children
。这样就为您提供了一个List[JValue]
,然后有一个更通用的map
方法,因为List
可以容纳任何类型。其类型签名为:
def map[B](f: A => B): List[B]
因此您可以这样做:
val storesWithSales = salesArray.children.map(sale => compact(render(sale)))