Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Types in Scala, Long, Int, etc.

Tags:

scala

Please type this in.

scala> 86400000 * 150 res0: Int = 75098112   scala> val i : Long = 86400000 * 150 i: Long = 75098112     val i  = 86400000 * 150.asInstanceOf[Long] i: Long = 12960000000  val i  = 86400000 * 150L i: Long = 12960000000 

What in the world is going on here? I've been skydiving and I must say that this is the most dangerous thing I've ever seen. No compiler check for this? Obviously if I was substituting 150 for a variable that's different.

*EDIT*

This was the actual code that got me worried.

val oneDay = 86400000 val days150 = oneDay * 150  days150 = 75098112 

This was not Scala's fault or anyones fault except my own. Just got me worried.

like image 212
Drew H Avatar asked Dec 20 '11 17:12

Drew H


People also ask

What are decimal types in Scala?

Scala Numeric Types Numeric type in Scala deals with all types that are stored in numerical. The data type that is used is decimals (float and Double) and integers (Int, Short, Long).

What is a long in Scala?

In Scala, Long is a 64-bit signed integer, which is equivalent to Java's long primitive type. The *(x: Long) method is utilized to return the product of the specified Long value and Long value.

What is unit data type in Scala?

The unit type is a child class of any type in the trait. This is used with the method signature in the scala as a return value. We should use this when we do not want our function to return any value.


1 Answers

There's nothing Scala-specific about this. It's just a matter of the target type of the assignment being irrelevant to the type in which an operation (multiplication in this case) is performed.

For example, in C#:

using System;  class Program {     static void Main(string[] args)     {         int a = unchecked(86400000 * 150);         long b = unchecked(86400000 * 150);         long c = 86400000 * (long) 150;         long d = 86400000 * 150L;         Console.WriteLine(a); // 75098112         Console.WriteLine(b); // 75098112         Console.WriteLine(c); // 12960000000         Console.WriteLine(d); // 12960000000     } } 

The unchecked part here is because the C# compiler is smart enough to realize that the operation overflows, but only because both operands are constants. If either operand had been a variable, it would have been fine without unchecked.

Likewise in Java:

public class Program {     public static void main(String[] args)     {         int a = 86400000 * 150;         long b = 86400000 * 150;         long c = 86400000 * (long) 150;         long d = 86400000 * 150L;         System.out.println(a); // 75098112         System.out.println(b); // 75098112         System.out.println(c); // 12960000000         System.out.println(d); // 12960000000     } } 
like image 51
Jon Skeet Avatar answered Sep 27 '22 23:09

Jon Skeet