2

This Stackoverflow post discusses the potential problem of a numeric overflow if not appending L to a number:

Here's an example from the REPL:

scala> 100000 * 100000 // no type specified, so numbers are `int`'s
res0: Int = 1410065408

One way to avoid this problem is to use L.

scala> 100000L * 100000L
res1: Long = 10000000000

Or to specify the number's types:

scala> val x: Long = 100000
x: Long = 100000

scala> x * x
res2: Long = 10000000000

What's considered the best practice to properly specify a number's type?

Community
  • 1
  • 1
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

1 Answers1

10

You should always use L if you are using a long. Otherwise, you can still have problems:

scala> val x: Long = 10000000000
<console>:1: error: integer number too large
       val x: Long = 10000000000
                     ^

scala> val x = 10000000000L
x: Long = 10000000000

The conversion due to type ascription happens after the literal has been interpreted as Int.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • Why doesn't `100000 * 100000` get stored in a data structure that can hold the value *without* overflowing? Is it a high burden on the programming language writer? – Kevin Meredith Jan 27 '14 at 18:33
  • 1
    @KevinMeredith In some languages, it does. Scala follows Java convention and types, which was inherited from C by way of C++, and defaults to numeric types that can be efficiently manipulated by the CPU -- with direct translations into machine code, often enough. – Daniel C. Sobral Jan 27 '14 at 21:14