您的隐式转换不适用,因为您的隐式转换将转换Option[Object]
为Option[Int]
,但您的代码似乎期望它转换Object
为Option[Int]
.
尝试包装_items get( "Bar" )
withSome()
以获得 anOption[Object]
而不仅仅是 anObject
并查看您的隐式转换是否开始。
编辑:实际上,我不确定为什么这对您不起作用,因为(正如您在评论中正确指出的那样),Scala 映射返回选项。以下代码适用于我并打印“37”,正如我所期望的那样:
import scala.collection.mutable.Map
import scala.collection.mutable.HashMap
object ImplicitConversions {
implicit def asInt( _in:Option[Object] ) = _in.asInstanceOf[Option[Int]]
implicit def asDouble( _in:Option[Object] ) = _in.asInstanceOf[Option[Double]]
private def foo( _items:Map[String,Object] ) = {
val bar:Option[Int] = _items.get("Bar")
println(bar.get.intValue)
}
def main(args: Array[String]) {
val map:Map[String,Object] = new HashMap[String, Object]
map.put("Bar", Integer.valueOf(37))
foo(map)
}
}
但是,如果我使用 Java 映射,则使用以下方法进行包装Some()
:
import java.util.Map
import java.util.HashMap
object ImplicitConversions {
implicit def asInt( _in:Option[Object] ) = _in.asInstanceOf[Option[Int]]
implicit def asDouble( _in:Option[Object] ) = _in.asInstanceOf[Option[Double]]
private def foo( _items:Map[String,Object] ) = {
val intermediate = Some(_items.get("Bar"))
val bar:Option[Int] = intermediate
println(bar.get.intValue)
}
def main(args: Array[String]) {
val map:Map[String,Object] = new HashMap[String, Object]
map.put("Bar", Integer.valueOf(37))
foo(map)
}
}
(请注意,我确实必须将结果存储Some()
在中间变量中才能使转换正常工作-也许 Scala 方面的专家可以告诉我如何避免该中间步骤。;-))
Scala 和 Java 映射是否可能在您的代码中混在一起?您确实说过您正在调用遗留 Java 代码,这就是为什么您必须首先进行所有这些隐式转换的原因。如果您认为您使用的是 Scala 映射时使用的是 Java 映射,那么这将解释此处的断开连接。