为什么 Scala 定义了一个“+="?Short 和 Byte 类型的运算符? [英] Why does Scala define a "+=" operator for Short and Byte types?

查看:47
本文介绍了为什么 Scala 定义了一个“+="?Short 和 Byte 类型的运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下 Scala 代码:

Given the following scala code:

var short: Short = 0
short += 1        // error: type mismatch
short += short    // error: type mismatch
short += 1.toByte // error: type mismatch

我不质疑底层类型 - 很明显Short + value == Int".

I don't questioning the underlying typing - it's clear that "Short + value == Int".

我的问题是:
1.有没有什么方法可以使用运算符?
2. 如果没有,那么为什么运营商可以在 Short & 上使用?字节?

My questions are:
1. Is there any way at all that the operator can be used?
2. If not, then why is the operator available for use on Short & Byte?

[并且通过扩展 *=、|= &= 等]

[And by extension *=, |= &=, etc.]

推荐答案

问题好像是Short class上的+(Short)"定义为:

The problem seems to be that "+(Short)" on Short class is defined as:

def +(x: Short): Int

所以它总是返回一个 Int.

So it always returns an Int.

鉴于此,您最终无法使用 += "operator",因为 + 操作计算为一个 Int,该 Int(显然)不能分配给脱糖版本中的short"var:

Given this you end up not being able to use the += "operator" because the + operation evaluates to an Int which (obviously) can not be assigned to the "short" var in the desugared version:

short = short + short

至于你的第二个问题,它是可用的",因为当 Scala 编译器找到如下表达式时:

As for your second question, it is "available" because when the scala compiler finds expressions like:

x K= y

如果 x 是一个 var 并且 K 是任何符号运算符,并且在 x 中有 K 方法,那么编译器将其翻译或脱糖"为:

And if x is a var and K is any symbolic operator and there is K method in x then the compiler translates or "desugar" it to:

x = x K y

然后尝试继续编译.

这篇关于为什么 Scala 定义了一个“+="?Short 和 Byte 类型的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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