在 Scala 中,'val a: A = _'(下划线)到底是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8336640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:43:25  来源:igfitidea点击:

In Scala, what exactly does 'val a: A = _' (underscore) mean?

scalainitialization

提问by Gregor Scheidt

What exactly does val a: A = _initialize a value to? Is this a typed null? Thanks.

这到底是什么val a: A = _初始化值?这是一个类型化的空值吗?谢谢。

回答by Paul Butcher

val a: A = _is a compile error. For example:

val a: A = _是编译错误。例如:

scala> val a: String = _
<console>:1: error: unbound placeholder parameter
       val a: String = _
                       ^

What does work is var a: A = _(note varinstead of val). As Chuck says in his answer, this initialises the variable to a default value. From the Scala Language Specification:

有效的是var a: A = _(注意var而不是val)。正如查克在他的回答中所说,这会将变量初始化为默认值。来自 Scala 语言规范:

0 if T is Int or one of its subrange types,
0L if T is Long,
0.0f if T is Float,
0.0d if T is Double,
false if T is Boolean,
() if T is Unit,
null for all other types T.

0 如果 T 是 Int 或其子范围类型之一,
0L 如果 T 是 Long,
0.0f 如果 T 是 Fl​​oat,
0.0d 如果 T 是 Double,
false 如果 T 是 Boolean,
() 如果 T 是 Unit,
所有其他类型为 null T。

回答by Chuck

It initializes ato the default value of the type A. For example, the default value of an Int is 0 and the default value of a reference type is null.

它初始化a为类型的默认值A。例如,Int 的默认值为 0,引用类型的默认值为 null。