Help in scala programming

Hello guys , I’m new to Scala programming language but i found something made me confused

when we define a Varibale with a long type like that :

var num:Long = 1000_000_000_000

we got an error message , because the compiler thinks that value is an int value , so we need to put “L” after the value , and when we write this code :

var num:Long = 10

we didn’t get any error massage because the compiler changes the type of the value using “type Casting”

so why we don’t get any error message if write code like that :

var num:Short = 10

and we know that “type Casting” is impossible from int to short

And sorry for my bad English


There are different issues at play here.

First, you tried to use an integer literal, but 1000_000_000_000 by itself is way too large to be represented as an Int. This has nothing to do with the declared type of the val.

In your second statement, there is type promotion at play. Meaning the compiler helpfully widens the type of an value to a more general type without losing information about the magnitude of the value.

The third statement is also the compiler being able to deduce that the value of the integer literal fits into the value range of a short integer and helpfully coerces the value to Short. If the value would be to large, you also get a compiler error.

But I know that type Casting from int to short is impossible
I mean in the code number 3 :

var num:Short = 10

does the compiler change the value 10 from int to short ?
because if we write code like that :

val num:Int = 10
val num2:Short = num

we got an error , that mean the compiler can’t change the int value type to short value type , so how does he changed the type of value 10 from int to short ?

As @cbley said, what is happening here is that the compiler is being helpful with literals. The numeric literal 10 is by default parsed as an Int, so it can’t have too large a value, but it is also a perfectly happy value for Long, Double, Float, Short, and Byte types. So when the compiler sees that literal value used in a position that needs a Short or a Byte, instead of forcing you to do a conversion manually, it will interpret the literal as a smaller numeric type.

This type of thing only makes sense for literals though. If you have an expression that explicitly evaluates to an Int, like your variable num, it isn’t safe to change that implicitly. That requires an explicit conversion. The reason for this is that unlike the literal, you don’t generally know what went into the calculation of some arbitrary Int expression, so determining if it fits in the range of some smaller type is basically a non-computable problem. The only way to know is to run the program and have an explicit type coercion that hopefully includes a check to make sure that it was valid.

1 Like

Ok thx I got it now , so literal values can be change to byte or short unlike Variable s