मैं दावा नहीं कर रहा हूं कि यह सब सुरुचिपूर्ण है, लेकिन यह काम करता है। मैं थोड़ा सा मदद करने के लिए टाइप अनुमान को अनुमति देने के लिए स्पष्ट रूप से JavaConversions
से रूपांतरणों का उपयोग करता हूं। JavaConversions
स्कैला 2.8 में नया है।
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: _*)
अद्यतन: यहाँ एक वैकल्पिक दृष्टिकोण 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]]]]]
}
}
क्या यह एक और अधिक डिज़ाइन समस्या नहीं है? इस संरचना का अर्थशास्त्र क्या है? आप वस्तुओं को कन्वर्ट क्यों करना चाहते हैं? –
असल में मैं जैक्सन जेसन लाइब्रेरी के माध्यम से एक जेसन फ़ाइल से यह डेटा पढ़ रहा हूं (मैंने कोशिश की कि एसजेसन और लिफ्ट-जेसन दोनों ने मुझे असफल कर दिया)। जैक्सन जेसन के पास स्कैला एपीआई नहीं है इसलिए मैंने नौकरी करने के लिए जावा एपीआई का इस्तेमाल किया। –