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?

3
  • 1
    This is really an opinion question. There is no universally accepted best practice for this. I'd just use the L suffix. Commented Jan 27, 2014 at 16:10
  • 2
    This isn't a matter of opinion. Adding an L specifies the right type, using ascription converts it afterwards. Commented Jan 27, 2014 at 18:27
  • 1
    In light of Daniel's comment, why am I getting down-votes? Commented Jan 27, 2014 at 18:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.