스칼라가 왜 유추 할 수있는 것들을 허용하지 않는지 매우 혼란 스럽습니다. 임의의 타입을 맵에 저장하고 싶다면 가능해야하지만 작업을 수행하기에 충분한 정보가있는 곳에서는 차단되어야한다고 상상해보십시오.스칼라 맵을 사용하는 방법
scala> var m: Map[Any, Any] = Map()
m: Map[Any,Any] = Map()
scala> m = ("one" -> 1, 2 -> "two", 3 -> 3)
<console>:8: error: type mismatch;
found : ((String, Int), (Int, String), (Int, Int))
required: Map[Any,Any]
m = ("one" -> 1, 2 -> "two", 3 -> 3)
^
scala> m += ("one" -> 1)
scala> m += (2 -> "two")
scala> m += (3 -> 3)
scala> m
res25: Map[Any,Any] = Map(one -> 1, 2 -> two, 3 -> 3)
scala> m("one").getClass
res26: Class[_] = class java.lang.Integer
scala> m(3).getClass
res27: Class[_] = class java.lang.Integer
scala> val result = m("one")+m(3)
<console>:8: error: type mismatch;
found : Any
required: String
val result = m("one")+m(3)
^
scala> val result: Int = m("one")+m(3)
<console>:8: error: type mismatch;
found : Any
required: String
val result: Int = m("one")+m(3)
^
scala> val mr1 = m("one")
mr1: Any = 1
scala> val mr1 = m("one") => Int
<console>:1: error: not a legal formal parameter.
Note: Tuples cannot be directly destructured in method or function parameters.
Either create a single parameter accepting the Tuple1,
or consider a pattern matching anonymous function: `{ case (param1, param1) => ... }
val mr1 = m("one") => Int
^
는 궁극적으로 나는 키 (문자열)의 유형을 알고, 그 값의 실제 유형을 알 수 있기 때문에, 나는 적어도 오른쪽을 캐스팅 할 수 있어야한다? 나는 또한 코드가 타입 안전해야한다는 것을 알고있다.
분명히 여기있는 대부분의 오류와 재판을하고 있습니다. 누구든지 안내를 제공 할 수 있습니까?
그래, 더 많은 시행 착오를 발견했습니다. 'var mr2 = mr1.asInstanceOf [java.lang.Integer]' – pferrel