Avoiding Overflow

long-integer, scala

Solution

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`.

Problem

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?

Original source

Related problems