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
有没有其他更加优雅的写法呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你的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编译器会把它当做基本类型来使用。3.instanceOf[Integer]也不好看 凑合用吧
如果你只写一次,可以用
instanceOf如果需要写很多次,可以利用隐式转换简化,更简单的方式是写个辅助的函数