Skip to content

Fix #240: Document formatter behavior for negative hexadecimals #632

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions doc/semantics.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,28 @@ As a consequence, the following apparent subtyping relationships hold:
Byte <:< Short <:< Int <:< Double
<:< Float <:<

#### Implications for formatting negative values in hexadecimal

Because there is no runtime difference between `Byte` `Short` and `Int`s (for sufficiently low values),
`java.util.Formatter` (and hence all formatting strings) assume `Int` to determine the padding when formatting negative hexadecimal values.

This leads to the following difference in format output:

{% highlight scala %}
val b: Byte = -38.toByte
"%x".format(b)
// JVM: "da"
// Scala.js: "ffffffda"
{% endhighlight %}

To achieve portable code, convert the value to an unsigned int first:

{% highlight scala %}
val b: Byte = -38.toByte
"%x".format(b & 0xff)
// "da" on both platforms
{% endhighlight %}

### `getClass()`

In Scala/JVM as well as Scala.js, when assigning a primitive value to an `Any` (or a generic type), and asking for its `getClass()`, Scala returns the *boxed class* of the value's type, rather than the primitive value.
Expand Down