Scala如何将Int转换为Double?
val d: Double = 42 当我试图通过intellij找到隐式转换时,没有任何有趣的东西出现.此外,Int不是Double的子类型.那么Scala是如何做到的呢? 解决方法
长话短说:它不是对某些伴随物体的普通隐式转换,数值类型得到特殊处理.
如果我们在这个脚本上运行scala -print: val d: Double = 42 我们获得: package <empty> { object Main extends Object { def main(args: Array[String]): Unit = { new <$anon: Object>(); () }; def <init>(): Main.type = { Main.super.<init>(); () } }; final class anon$1 extends Object { private[this] val d: Double = _; <stable> <accessor> private def d(): Double = anon$1.this.d; def <init>(): <$anon: Object> = { anon$1.super.<init>(); anon$1.this.d = 42.0; () } } } 在desugared代码中,我们看到双字42.0,但没有任何转换的调用 section 3.5.3 of the specification Int <:w Long <:w Float <:w Double 此外,Section 6.26.1 (Value Conversions) >表达式e = 42 因此,使用toDouble将42转换为42.0.因为它是一个可以在编译时处理的常量, val d: Double = (new scala.util.Random).nextInt(42) 我们获得: package <empty> { object Main extends Object { def main(args: Array[String]): Unit = { new <$anon: Object>(); () }; def <init>(): Main.type = { Main.super.<init>(); () } }; final class anon$1 extends Object { private[this] val d: Double = _; <stable> <accessor> private def d(): Double = anon$1.this.d; def <init>(): <$anon: Object> = { anon$1.super.<init>(); anon$1.this.d = new scala.util.Random().nextInt(42).toDouble(); () } } } 并且指定了toDouble. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- angularjs – “ng-options”上“跟踪”的目的是什么
- 春天 – Thymeleaf Boot AngularJS指令解析器错误
- webservice cxf 学习,重点是加密
- Angular的Kendo UI:无法绑定到’primary’,因为它不是’bu
- 数组 – 在Scala映射数组时如何获取元素索引?
- 如何存储grep命令结果在shell中的一些变量
- angularjs – Angular / Breeze SPA模板上的UnMapped属性
- 机器学习技法总结(四)(aggregation,vote,bootstrap...
- Bootstrap笔记—折叠实例代码
- 《第24天》mysql和sqlite讲解以及python操纵