1

I want to access the barcode variable from the addItemToStore method and change the string to be "" in the clearPressed method, but I am having trouble figuring out how to call the variable from the method.

class SelfCheckout {
  var numList = List[String]()
  var numEnter: String = ""
  var clearBarcode: String = ""
  def addItemToStore(barcode: String, item: Item): Unit = {
    
  }

  def numberPressed(number: Int): Unit = {
    numList = numList :+ number.toString

  }

  def clearPressed(): Unit = {
    numList = List()
    
  }
1
  • 2
    Do not use var rather design according immutability. Commented Oct 18, 2022 at 8:59

1 Answer 1

1

You can use the = operator to assign something to a variable. What you are trying to do is achieved in the following code:

class SelfCheckout {
  var numList = List[String]()
  var numEnter: String = ""
  var clearBarcode: String = ""
  def addItemToStore(barcode: String, item: Item): Unit = {
    clearBarcode = barcode // HERE...
  }

  def numberPressed(number: Int): Unit = {
    numList = numList :+ number.toString

  }

  def clearPressed(): Unit = {
    numList = List()
    clearBarcode = "" // ..AND HERE
  }
}

The following tests pass, giving you confidence that the changes have the effect you were looking for:

val checkout = new SelfCheckout

assert(checkout.clearBarcode == "")

checkout.addItemToStore("some_barcode", item)

assert(checkout.clearBarcode == "some_barcode")

checkout.clearPressed()

assert(checkout.clearBarcode == "")

If you want to play around with this code, you can find it here on Scastie.

As a side note, someone in a comment mentioned that you may probably want to consider the idea of designing your object to be immutable. That's a very useful programming concept that enables you to more easily write code which is easy to test and run in parallel. Immutability is a very important concept in Scala, because many parts of its ecosystem (including its powerful Collection API) rely on the concept. You might want to read more about immutability on the Scala book here, but you'll find a lot of resources on the matter with a simple search.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.