声明一个没有初始值的变量 [英] Declare a variable without an initial value

查看:63
本文介绍了声明一个没有初始值的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

var myVar :Int;  
val myVal :String;

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

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

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;

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

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.

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

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

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

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

推荐答案

错误是正确的,您只能在抽象类或特征上执行此操作.本教程可能假设您在抽象类中编写该代码.

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 = _

但这本质上是一样的:

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

这篇关于声明一个没有初始值的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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