How many bytes in a Scala Char?

Viewed 274

So, today I learned I can fit at least three bytes in a Scala Char.

scala> "䕖".charAt(0)
val res4: Char = 䕖

How is this possible, where is this documented?

1 Answers

The Scala Language Specification does not specify any particular size for the numeric subrange value types. It only specifies the existence of certain implicit conversions, as well as certain methods.

In particular, the SLS specifies the following relationship of implicit conversions:

Byte - Short
             \
               Int - Long - Float - Double
             /
        Char

This implies but does not specify that the range of scala.Char is NOT-GREATER-THAN the range of scala.Int. However, that is all that is guaranteed about the range of scala.Char.

The Scala Standard Library documentation has the following to say about scala.Char:

Char, a 16-bit unsigned integer (equivalent to Java's char primitive type) is a subtype of scala.AnyVal. Instances of Char are not represented by an object in the underlying runtime system.

There is an implicit conversion from scala.Char => scala.runtime.RichChar which provides useful non-primitive operations.

It is, however, not clear to me whether this documentation is meant as a specification that all implementations of Scala must comply with, or a description of what this particular implementation of Scala does.

So, according to the Scala Language Specification, the size of a scala.Char can be pretty much anything. According to the Scala Standard Library Documentation, the size of a scala.Char is 16 bits, however it is not clear whether that is guaranteed for all Scala implementations, or if it only applies to Scala-JVM.

Related