我並不是說這一切都是優雅的,但它的工作原理。我明確而非隱含地使用來自JavaConversions
的轉換來允許類型推斷稍微有所幫助。在Scala 2.8中新增了JavaConversions
。
import collection.JavaConversions._
import java.util.{ArrayList, HashMap}
import collection.mutable.Buffer
val javaMutable = new HashMap[String, ArrayList[ArrayList[Double]]]
val scalaMutable: collection.Map[String, Buffer[Buffer[Double]]] =
asMap(javaMutable).mapValues(asBuffer(_).map(asBuffer(_)))
val scalaImmutable: Map[String, List[List[Double]]] =
Map(asMap(javaMutable).mapValues(asBuffer(_).map(asBuffer(_).toList).toList).toSeq: _*)
UPDATE:下面是一個使用implicits一組給定的轉換應用到任意嵌套結構的另一種方法。
trait ==>>[A, B] extends (A => B) {
def apply(a: A): B
}
object ==>> {
def convert[A, B](a: A)(implicit a2b: A ==>> B): B = a
// the default identity conversion
implicit def Identity_==>>[A] = new (A ==>> A) {
def apply(a: A) = a
}
// import whichever conversions you like from here:
object Conversions {
import java.util.{ArrayList, HashMap}
import collection.mutable.Buffer
import collection.JavaConversions._
implicit def ArrayListToBuffer[T, U](implicit t2u: T ==>> U) = new (ArrayList[T] ==>> Buffer[U]) {
def apply(a: ArrayList[T]) = asBuffer(a).map(t2u)
}
implicit def HashMapToMap[K, V, VV](implicit v2vv: V ==>> VV) = new (HashMap[K, V] ==>> collection.Map[K, VV]) {
def apply(a: java.util.HashMap[K, V]) = asMap(a).mapValues(v2vv)
}
}
}
object test {
def main(args: Array[String]) {
import java.util.{ArrayList, HashMap}
import collection.mutable.Buffer
// some java collections with different nesting
val javaMutable1 = new HashMap[String, ArrayList[ArrayList[Double]]]
val javaMutable2 = new HashMap[String, ArrayList[HashMap[String, ArrayList[ArrayList[Double]]]]]
import ==>>.{convert, Conversions}
// here comes the elegant part!
import Conversions.{HashMapToMap, ArrayListToBuffer}
val scala1 = convert(javaMutable1)
val scala2 = convert(javaMutable2)
// check the types to show that the conversion worked.
scala1: collection.Map[String, Buffer[Buffer[Double]]]
scala2: collection.Map[String, Buffer[collection.Map[String, Buffer[Buffer[Double]]]]]
}
}
這不是更多的設計問題嗎?這種結構的語義是什麼?你爲什麼要轉換對象? – 2010-02-13 13:38:49
其實我正在通過傑克遜json庫從json文件讀取這些數據(我試過sjson和lift-json都失敗了)。傑克遜json沒有scala API,所以我使用java API來完成這項工作。 – 2010-02-13 22:08:12