问题描述
这是我的问题的简单示例代码.
Here is a simple sample code for my question.
var a:Int=1;//第1行
var a:Int=1; //line 1
var a=1;//第2行
var a=1; //line 2
是否需要第 1 行中的 Int?还是必须?如果没有,我可以像第 2 行那样删除它吗?
Is Int in line 1 needed? or must?if not ,can I delete it like in line 2?
推荐答案
由于 1
是 Int
类型,编译器知道 a
是也是 Int
类型.这称为类型推断.
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.
在 Scala 中,类型推断可以双向进行,从右到左,反之亦然.例如在 val a = 1
中 a
的类型是从 1
的类型推断出来的,所以类型推断是从右到左的.在
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()
因为 n
应该是 Int
,编译器推断 myMethod()
中的 T
应该是Int
也是,所以类型推断是从左到右的.
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
这篇关于在scala中声明变量时什么时候需要显式类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!