All of these suggestions are nice, but at the end of the day, they’re asking a lot from what the language accepts as a literal. My proposal is just to allow
_ within literals, with no extra syntactic or semantic meaning. This is not meant to make it possible to write
BigDecimal or IP literals; just to make it easier to read existing number literals.
If you’re writing a library that uses a lot of binary or hex constants for fancy bitwise magic, or numeric constants for mathematical witchcraft, adding an
_ periodically in the literal can drastically improve readability.
val magicNumber = 0b10000001010001100000000000100001
val magicNumber = 0b_1000_0001_0100_0110_0000_0000_0010_0001
The latter separates the 32bit number into 4bit chunks, making it easier to process the number mentally without accidentally skipping a bit or losing track of whether you’re at the 17th or 18th bit.
You might even add extra
_s in the middle to break up the sections even more visibly (since there are 8 of them, which is a decent number)
val magicNumber = 0b_1000_0001_0100_0110__0000_0000_0010_0001
I would like to keep this proposal to the bare minimum of improving readability of literals, without attempting to allow defining new literals for arbitrary types. I think it could be valuable to allow the definition of arbitrary literals as well, but that requires significantly more work and is a major language change, while being slightly more flexible with existing literals requires less design discussion and bikeshedding.