Scala 运算符的奇怪之处 [英] Scala operator oddity

查看:66
本文介绍了Scala 运算符的奇怪之处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 2 上调用 + 时,我得到一个 Int,但是当它使用显式方法调用完成时,我得到 Double.

When I invoke + on 2 I get an Int back, but when its done using explicit method call I get Double instead.

scala> 2+2
res1: Int = 4

scala> 2.+(2)
res2: Double = 4.0

似乎 .+() 是在隐式转换为 Double 的 Int 上调用的.

It seems that .+() is invoked on implicit converted Int to Double.

scala> 2.+
<console>:16: error: ambiguous reference to overloaded definition,
both method + in class Double of type (x: Char)Double
and  method + in class Double of type (x: Short)Double
match expected type ?
              2.+
                ^

为什么会这样?

推荐答案

原因不在显式方法调用中——通过编写 2.+ 你在左侧指定 Double 然后调用addition操作符:

The reason is not in explicit method call -- by writing 2.+ you specifying Double on the left side and then calling addition operator on it:

scala> 2.
res0: Double = 2.0

这篇关于Scala 运算符的奇怪之处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆