Surender Raja
Surender Raja

Reputation: 3599

In Scala,Why is it not possible to change the value of var variable with different datatype

I am learning scala, trying to understand var variable .

Look at my below code

scala> var id =10
id: Int = 10

scala> id ="surender"
<console>:12: error: type mismatch;
 found   : String("surender")
 required: Int
   id ="surender"

var is mutable, that means we can change the value, While changing the value do we need to stick with same datatype?

Does it mean statically typed language?

Upvotes: 1

Views: 2511

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170805

You can specify the type when creating a var (or a val):

var id: Any = 10 // Don't actually do this!
id = "surender" // works

If you don't, the compiler infers the type from the initializer (in this case type of 10 is Int). However, Scala is indeed statically typed and there is very little you can usefully do with something of type Any. This is more useful e.g. in this situation:

var x: Option[Int] = None
x = Some(10) // doesn't compile without the signature above

Upvotes: 1

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23532

Yes Scala is indeed a statically typed language. You can't reassign the data type at runtime.

The concept is called type safety and a lot people value it deeply. It is a matter of preference however.

Upvotes: 9

Related Questions