Since 1
属于类型Int
,编译器知道a
属于类型Int
也。
这称为类型推断。
You should当这对于代码可读性更好时,显式指定类型。
You must当编译器无法推断类型或有助于推断其他类型时指定类型。
在 Scala 中,类型推断可以双向进行,从右到左,反之亦然。例如在val a = 1
类型a
从类型推断出1
,因此类型推断是从右向左进行的。在
def myMethod[T](): T = ???
val n: Int = myMethod()
since n
预计将成为Int
,编译器推断T
in myMethod()
应该Int
同样,类型推断也是从左到右进行的。
https://twitter.github.io/scala_school/type-basics.html#inference https://twitter.github.io/scala_school/type-basics.html#inference
http://www.scala-lang.org/old/node/127 http://www.scala-lang.org/old/node/127
http://allaboutscala.com/tutorials/chapter-2-learning-basics-scala-programming/scala-tutorial-overview-scala-type-inference/ http://allaboutscala.com/tutorials/chapter-2-learning-basics-scala-programming/scala-tutorial-overview-scala-type-inference/
scala 如何推断变量的类型? https://stackoverflow.com/questions/46520990/how-does-scala-infers-the-type-of-a-variable/