在scala中声明变量时什么时候需要显式类型? [英] when does it need explicit type when declare variable in scala?

查看:37
本文介绍了在scala中声明变量时什么时候需要显式类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题的简单示例代码.

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?

推荐答案

由于 1Int 类型,编译器知道 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 = 1a 的类型是从 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

http://allaboutscala.com/tutorials/chapter-2-learning-basics-scala-programming/scala-tutorial-overview-scala-type-in​​ference/

scala 如何推断变量的类型?

这篇关于在scala中声明变量时什么时候需要显式类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆