Here is a simple sample code for my question.
var a:Int=1; //line 1
var a=1; //line 2
Is Int in line 1 needed? or must? if not ,can I delete it like in line 2?
Here is a simple sample code for my question.
var a:Int=1; //line 1
var a=1; //line 2
Is Int in line 1 needed? or must? if not ,can I delete it like in line 2?
Since 1
is of type Int
, compiler knows that a
is of type Int
too.
This is called type inference.
You should specify a type explicitly when this is better for code readability.
You must specify a type when compiler can't infer the type or when this helps to infer other types.
In Scala type inference can go in both directions, from right to left and vice versa. For example in val a = 1
type of a
is inferred from type of 1
, so type inference went from right to left. In
def myMethod[T](): T = ???
val n: Int = myMethod()
since n
is expected to be an Int
, compiler infers that T
in myMethod()
should be Int
too, so type inference went from left to right.
https://twitter.github.io/scala_school/type-basics.html#inference
http://www.scala-lang.org/old/node/127
http://allaboutscala.com/tutorials/chapter-2-learning-basics-scala-programming/scala-tutorial-overview-scala-type-inference/
How does scala infers the type of a variable?
You don't need to specify the type Int in this case, as it is inferred by the compiler.
There is plenty of documentation about type inference in scala. Check this out: http://docs.scala-lang.org/tour/local-type-inference.html
In most cases the Scala compiler can deduce types automatically. In these cases you do not have to explicitly define the type of your variable declaration.
var a = 1
is perfectly valid Scala code.
It is often recommended to declare explicitly the return types of public methods.