Skip to content

Commit 87e6a60

Browse files
authored
Merge pull request #491 from sjrd/document-primitive-getclass
Document the boxed classes of primitive types.
2 parents 11632e5 + 7386fda commit 87e6a60

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

doc/semantics.md

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@ However, a few differences exist, which we mention here.
1010

1111
## Primitive data types
1212

13-
All primitive data types work exactly as on the JVM, with the following three
14-
exceptions.
13+
All nine primitive data types of Scala, i.e., `Boolean`, `Char`, `Byte`, `Short`, `Int`, `Long`, `Float`, `Double` and `Unit`, work exactly as on the JVM, with the following four exceptions.
1514

1615
### Floats can behave as Doubles by default
1716

@@ -80,6 +79,21 @@ if strict-floats are enabled, or
8079

8180
otherwise.
8281

82+
### `getClass()`
83+
84+
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.
85+
For example, `(true: Any).getClass()` returns `classOf[java.lang.Boolean]`, not `classOf[scala.Boolean]`.
86+
87+
In Scala.js, for numeric types, and for the same reason that instance tests are based on values, the result will be the *smallest* boxed class that can store the value.
88+
Hence, `(5: Any).getClass()` will return `classOf[java.lang.Byte]`, while `(50000: Any).getClass()` will return `classOf[java.lang.Integer]`.
89+
90+
**Scala.js 1.x only:**
91+
Moreover, for `()` (unit), the result will be `classOf[java.lang.Void]` instead of `classOf[scala.runtime.BoxedUnit]` like the JVM.
92+
`scala.runtime.BoxedUnit` is an implementation detail of Scala on the JVM, which Scala.js does not emulate.
93+
Instead, it uses the more sensible `java.lang.Void`, as `Void` is the boxed class corresponding to the `void` primitive type, which is `scala.Unit`.
94+
This means that while `java.lang.Void` is not instantiable on the JVM, in Scala.js it has a singleton instance, namely `()`.
95+
This also manifests itself in `Array[Unit]` which is effectively `Array[java.lang.Void]` at run-time, instead of `Array[scala.runtime.BoxedUnit]`.
96+
8397
## Undefined behaviors
8498

8599
The JVM is a very well specified environment, which even specifies how some

0 commit comments

Comments
 (0)