如何在scala更改中创建变量?

时间:2013-03-28 04:30:46

标签: scala variables scope

所以我有这个变量currentPartNumber,它开始等于0.我想要发生的是在我的函数中,如果变量等于零,则将其更改为1并打印出文本。我的第二个函数也是一样 - 如果我的第一个函数中的变量更改为1并且等于1,我希望变量更改为2,打印出文本。

问题是:如何使用我想要的每个函数调用来更改变量?

var currentPartNumber = 0

def roomOne():Unit = {
   if (currentPartNumber < 1) {
      var currentPartNumber = 1
      println("You now have parts 1 of 4.")
     } else {
      println("This part cannot be collected yet.")
   {
   }


def roomTwo():Unit = {
   if (currentPartNumber = 1) {
      var currentPartNumber = 2
      println("You now have parts 2 of 4.")
     } else {
      println("This part cannot be collected yet.")
   {
   }

2 个答案:

答案 0 :(得分:3)

不要遮蔽变量:从函数内部删除var

var关键字声明 成员/变量。在这种情况下,名称与阴影来自外部范围的变量相同。因此,赋值(作为声明的一部分)对外部变量没有影响。

// no var/val - assignment without declaration
currentPartNumber = 2

另见:

答案 1 :(得分:1)

currentPartNumberroomOne()可以访问和修改它的类中声明roomTwo()

class Parts{
  var currentPartNumber = 0

  def roomOne():Unit = {
    if (currentPartNumber < 1) {
      currentPartNumber = 1
      println("You now have parts 1 of 4.")
    } else {
      println("This part cannot be collected yet.")
    } 
  }  

  def roomTwo():Unit = {
    if (currentPartNumber == 1) {
       currentPartNumber = 2
       println("You now have parts 2 of 4.")
     } else {
      println("This part cannot be collected yet.")
     }
   }
}



scala> :load Parts.scala
Loading Parts.scala...
defined class Parts
scala> var parts = new Parts
parts: Parts = Parts@5636a67c
scala> parts.currentPartNumber
res0: Int = 0
scala> parts.roomOne
You now have parts 1 of 4.
scala> parts.roomTwo
You now have parts 2 of 4.