我正在尝试编写一个小型包装类,以使Gson 库对 Scala 更加友好。不幸的是,当我尝试按照我想要的方式进行时,我遇到了编译错误。
这是我到目前为止的代码:
package com.test
import com.google.gson.{JsonObject, JsonElement}
import scala.collection.Iterator
import scala.collection.immutable.Map
case class GsonMap ( private val inner: JsonObject = new JsonObject )
extends Map[String, JsonElement] {
/** {@inheritDoc} */
override def iterator: Iterator[(String, JsonElement)]
= new Iterator[(String, JsonElement)] {
private val entries = inner.entrySet.iterator
override def hasNext: Boolean = entries.hasNext
override def next: (String, JsonElement) = {
val elem = entries.next
( elem.getKey, elem.getValue )
}
}
/**
* Returns a clone of the inner JsonObject
*/
private def cloneInner: JsonObject = {
val result = new JsonObject()
iterator.foreach { (item) => result.add( item._1, item._2 ) }
result
}
/** {@inheritDoc} */
override def + ( kv: (String, JsonElement) ): GsonMap = {
val cloned = cloneInner
cloned.add( kv._1, kv._2 )
GsonMap( cloned )
}
/** {@inheritDoc} */
override def get( key: String ): Option[JsonElement]
= Option( inner.get(key) )
/** {@inheritDoc} */
override def - ( key: String ): GsonMap = {
val cloned = cloneInner
cloned.remove( key )
GsonMap( cloned )
}
}
现在,我知道该+
方法与 Map 类中定义的不匹配。这就是问题所在,真的。我希望该+
方法接受JsonElement
s 并返回 a GsonMap
,但我不确定如何使其工作。我在这一点上尝试了一些变化,但没有运气
作为参考,这是我收到的编译错误:
[info] Compiling 1 Scala source to target/scala-2.9.2/classes...
[error] src/main/scala/GsonMap.scala:7: class GsonMap needs to be abstract, since method + in trait Map of type [B1 >: com.google.gson.JsonElement](kv: (String, B1))scala.collection.immutable.Map[String,B1] is not defined
[error] case class GsonMap ( val inner: JsonObject = new JsonObject )
[error] ^
[error] src/main/scala/GsonMap.scala:31: method + overrides nothing
[error] override def + ( kv: (String, JsonElement) ): GsonMap = {
[error] ^
[error] two errors found
有什么建议吗?
更新:
正如下面所建议的,这是我尝试过的变体之一:
override def +[T >: JsonElement] ( kv: (String, T) ): GsonMap = {
val cloned = cloneInner
cloned.add( kv._1, kv._2 )
GsonMap( cloned )
}
但是,它也失败了:
[info] Compiling 1 Scala source to target/scala-2.9.2/classes...
[error] /src/main/scala/GSON.scala:33: type mismatch;
[error] found : T
[error] required: com.google.gson.JsonElement
[error] cloned.add( kv._1, kv._2 )
[error] ^
[error] one error found
我对>:
运算符的理解是 T 必须是 JsonElement 的父级,我认为这不是我要找的。在这种情况下,此映射只能包含 JsonElements 的实例,因此不适合放入 JsonElements 的父项。