Mahesh Chand Kandpal Mahesh Chand Kandpal - 3 years ago 169
Scala Question

How does scala infers the type of a variable?

I am always fascinated to see how scala always infers the type correctly . How scala does it?

scala> val num = 5
num: Int = 5

scala> val num = "5"
num: String = 5

I know it might be a very stupid question to ask here but i don't know the answer.
Please enlighten me.

Answer Source

There are several methods for inferencing the type of a variable. Mainly using those called inference rules based in logic theory.

There are plenty of papers explaining the theory behind. Here I put a good example (with Scala ;) )

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download