为什么 Scala 不能从 Int 和 Double 推断出 Any 或 AnyVal 类型? [英] why doesn't scala infer type Any or AnyVal from Int and Double?

查看:34
本文介绍了为什么 Scala 不能从 Int 和 Double 推断出 Any 或 AnyVal 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 做了什么,然后就是为什么.

There is what scala does, and then there is why.

我的问题是为什么 Scala 更喜欢将 Int 转换为 Double 而不是推断 AnyVal 或 Any:

My question is why does scala prefer to convert the Int to Double rather than infer AnyVal or Any:

// test1:
scala> val foo = if (true) 5 else 5.0
foo: Double = 5.0 // Why isn't this AnyVal or Any ?

// I can force it this way... once I realized this was my problem.
scala> val foo: Any = if (true) 5 else 5.0
foo: Any = 5

// or this way, which is better actually
scala> val bar : java.lang.Number = if (true) 5 else 5.0
bar: Number = 5

但我的问题不是它的作用,而是为什么将 Int 转换为 Double 的行为是正确或合理的?

But my question isn't what it does, but why is the behavior of converting the Int to Double correct or rational?

我浪费了相当多的时间来找出导致错误的原因,为了将来避免这种情况,我想为这些转换开发一些直觉.

I wasted quite a bit of time isolating this as what was causing a bug, and to avoid this in the future I'd like to develop some intuition for these conversions.

推荐答案

这叫做数字加宽.请参阅 SLS 6.23.1 - 值转换:

如果 e 的原始数字类型与预期类型弱符合,则使用此处定义的数字转换方法之一 toShort、toChar、toInt、toLong、toFloat、toDouble 将其扩展为预期类型.

If e has a primitive number type which weakly conforms to the expected type, it is widened to the expected type using one of the numeric conversion methods toShort, toChar, toInt, toLong, toFloat, toDouble defined here.

弱一致性SLS 3.5.3:

Byte  <:w Short
Short <:w Int
Char  <:w Int
Int   <:w Long
Long  <:w Float
Float <:w Double

Int(传递地)弱符合 Double,因此编译器推断 Double 而不是 AnyVal,并且使用 Int#toDouble 进行转换.

Int (transitively) weakly conforms to Double, so the compiler infers Double instead of AnyVal, and uses Int#toDouble to make the conversion.

为什么没问题?您实际上还没有提出由此引起的错误.只要遵循弱一致性关系,类型转换就不会丢失任何信息.推断 Double 而不是 AnyVal 更有意义,因为你会丢失原本可以保留的类型信息(因为 AnyVal 不一定是一个号).

Why is this okay? You haven't actually presented a bug caused by this. As long as the weak conformance relation is followed, the type conversions will not lose any information. It makes more sense to infer Double instead of AnyVal, because you lose type information you could have otherwise kept (as AnyVal isn't necessarily a number).

这篇关于为什么 Scala 不能从 Int 和 Double 推断出 Any 或 AnyVal 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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