Why does Scala define a “+=” operator for Short and Byte types?

孤人 提交于 2020-01-02 04:09:05

问题


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

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

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.]


回答1:


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

def +(x: Short): Int

So it always returns an Int.

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

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

x K= y

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

And then tries to continue compilation with that.



来源:https://stackoverflow.com/questions/10975245/why-does-scala-define-a-operator-for-short-and-byte-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!