props.put("retries", 3)
报错,对于这种字面值如何指定类型呢?
Error:(13, 24) type mismatch;
found : Int(3)
required: Object
Note: an implicit exists from scala.Int => java.lang.Integer, but
methods inherited from Object are rendered ambiguous. This is to avoid
a blanket implicit which would convert any scala.Int to any AnyRef.
You may wish to use a type ascription: `x: java.lang.Integer`.
props.put("retries", 3)
只能按照使用一个临时变量吗? val x : java.lang.Integer = 3
有没有其他更加优雅的写法呢?
你的props
是什么Map
? 把完整的代码放上来吧,这样大家可以知道的更清楚。具体可以看这里: http://stackoverflow.com/ques...
大意就是: Sala 的 Int (extend AnyVal) 与 Java.lang.Integer (extend AnyRef) 的继承关系是不一样的。如果直接转换,可能会造成一些想不到的错误。比如针对
notify
方法。而
Properties
是 Java 中的类,它希望的 Key 是 Object,也就是 Scala 中的AnyRef
。因此,Scala编译器为了防止后续的错误使用,就报错来提醒你了。P.S.
AnyVal
简单来说,就是为了避免拆箱装箱的开销的。我们在写程序时可以将它看成对象,但Scala编译器会把它当做基本类型来使用。