5

Consider this code:

val x1: Byte = 0x00
val x2: Byte = 0x01
val x3: Byte = x1 + x2;

This gives a compile error, because the result of adding 2 Bytes is an Int.

To work around this, I need to manually cast the result back into a byte:

val x3: Byte = (x1 + x2).toByte()

This is very counter-intuative. Why do the arithmetic operators work like this?

Tiddo
  • 6,331
  • 6
  • 52
  • 85
  • 2
    `Why do the arithmetic operators work like this?` is very hard to answer without asking the developers of Kotlin. It's just the way it's defined: `public operator fun plus(other: Byte): Int` – Zoe Oct 17 '18 at 08:45
  • 2
    because Java (as well as other C-like languages) promotes types narrower than int to int [Why byte and short values are promoted to int when an expression is evaluated](https://stackoverflow.com/q/27582233/995714), [Why byte and short division results in int in Java?](https://stackoverflow.com/q/41034555/995714), [Why are integer types promoted during addition in C?](https://stackoverflow.com/q/29817927/995714), [Why must a short be converted to an int before arithmetic operations in C and C++?](https://stackoverflow.com/q/24371868/995714) – phuclv Oct 17 '18 at 09:45

1 Answers1

8

This is very counter-intuative. Why do the arithmetic operators work like this?

It is also an exact copy of the Java semantics. Java has no bytecode for the addition of two bytes, chars or shorts. While Kotlin could have decided to change the semantics and emit more complex bytecode, the choice to stay aligned with Java has its merits.

A similar question would be "why is Byte a signed type?" and the answer would be along similar lines. Kotlin is intended to feel familiar to experienced Java developers.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436