Scala implicit conversion called twice -
I'm trying to institute classes of maps [string, Annie], through which some Jesan-RPC Is obtained. So I end the following problem:
val mpa: map [string, any] = map ("key" -> 0.0) Built-in def anyToInt (a: Any): Int = A .asInstanceOf [double] .toInt
The key is present all right
Val I:. Int = mpa.getOrElse ("key", 0.0) I: Int = 0
But when the key is unavailable ...:
scala> ; Val I: Int = mpa.getOrElse (not molded in "Val", 0.0) java.lang.Double on scala.runtime.BoxesRunTime.unboxToDouble (Unknown Source) at JavaklangkClassCastException: JavaklangkInteger KanyToInt be can (& lt; console & gt ;: 13
now, we are adding some verbiage such as:
implicit def anyToInt (a : Any): int = {println (a) value b = a.asInstanceOf [double] .toInt println ("changed") b}
We found:
< pre> val i: Int = mpa.getOrElse ( "VAL", 0.0) 0.0 change 0 java.lang.ClassCastException: java.lang.Integer java.lang.Double the .....
< / Pre> Question:
-
Why ?!
-
What should I do to avoid this?
PS: Sorry, If this is a newbie question.
hidden direct conversion and especially any
As it is in your case, it is a very bad idea and you know Defense is why I advise you to convert map [string Inti]
to your input map. You do not need a performance here, but if you still want to go with the underlying, then you should do it with the cover:
built-in def anyExtender (x: Any) = new {def ToInt = x match {case x: double = & gt; X.toInt}}
and use it like this:
mpa.getOrElse ("val", 0.0) .toInt
< / Pre>since it was like following the implementation of the underlying cover Scale 2.10:
underlying class AnyExtender (x: Any) {def toInt = x match {case x : Double = & gt; X.toInt}}
Still, your conversion function does not work on all the subtypes of
any
, withany
Expanding is such a thing that such a function would be right to increase thedouble
, but it is already there.map.getOrElse ( "VAL", 0.0) .asInstanceOf [double] .toInt
<: the only way this type of situation would be just using my map conversions for >updates
the map [string, ante] will work for you, if you move the logic that you want to keep in spreading this :
WAL ResultsMapStringToinType = InputMapStringToAnap.MapValue {Case X: Double => X.toInt case x: string = & gt; X.toInt case x: timestamp = & gt; // ... // and so on}
Comments
Post a Comment