scala 声明一个没有初始值的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37174687/
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 08:17:05  来源:igfitidea点击:

Declare a variable without an initial value

scala

提问by Matt C

This Scala tutorialhas the following to say about declaring variables without an initial value:

这个 Scala 教程有以下关于声明没有初始值的变量的内容:

If you do not assign any initial value to a variable, then it is valid as follows:

var myVar :Int;  
val myVal :String;

如果你没有给一个变量赋值任何初始值,那么它是有效的,如下所示:

var myVar :Int;  
val myVal :String;

But when I try that code in the Scala REPL, I get these errors:

但是当我在 Scala REPL 中尝试该代码时,我收到以下错误:

scala> var myVar :Int;
<console>:10: error: only classes can have declared but undefined members
(Note that variables need to be initialized to be defined)
       var myVar :Int;
           ^

scala> val myVal :String;
<console>:10: error: only classes can have declared but undefined members
       val myVal :String;

Why is this? Is the tutorial for an older version of Scala?
I couldn't find a specific version of Scala that the tutorial is written for, but I am running Scala version 2.11.7 on OpenJDK 64bit, Java 1.8.0_66.

为什么是这样?是旧版本 Scala 的教程吗?
我找不到本教程针对的特定 Scala 版本,但我在 OpenJDK 64 位 Java 1.8.0_66 上运行 Scala 版本 2.11.7。



  • Is the tutorial outdated, or is the problem with my environment?

  • Is it possible to declare a variable (var or val) without initializing it?

  • 是教程过时了,还是我的环境有问题?

  • 是否可以在不初始化的情况下声明变量(var 或 val)?

回答by Alvaro Carrasco

The error is correct, you can only do that on an abstract class or trait. The tutorial might be assuming that you are writing that code inside of an abstract class.

错误是正确的,您只能在抽象类或特征上这样做。本教程可能假设您正在抽象类中编写该代码。

It is possible to initialize variables to some default value:

可以将变量初始化为某个默认值:

var i: Int = _
var s: String = _

But that's essentially the same as:

但这本质上是一样的:

var i: Int = 0
var s: String = null