Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 740
Richard Sitze Avatar asked Nov 03 '22 22:11

Richard Sitze


1 Answers

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.

like image 163
Pablo Lalloni Avatar answered Nov 15 '22 06:11

Pablo Lalloni