Scala - Option Type Var Manipulation

313 views Asked by At

I am working on an online exercise practicing Options and threads, both of which I have very little experience. The online exercise comes with a test suite, so right now I am trying to get my Option test cases to pass before I move on to the thread test cases.

Here is my code:

case class BankAccount() {
  def getBalance = account.balance

  def incrementBalance(amount: Int): Option[Int] = {
    account.balance = Some(account.balance.get + amount)
    getBalance
  }

//  def closeAccount(): Option[Int] = {
//    account.balance = None: Option[Int]
//  }
}

object account {
  var balance = Some(0)
}

I have closeAccount() commented out because it is currently giving me an error saying that it is expecting type Some[Int] instead of Option[Int]. Understandable considering how I have initialized balance. I am not sure how to go from a value of Some[Int] to None as seen in closeAccount().

Any help would be appreciated in getting this figured out. Thank you in advance.

First Edit: I figured out what stupid mistake I was making with incrementBalance. Since getBalance was a val, it wasn't recalculating the value after manipulation. Still lost on closeAccount() though.

1

There are 1 answers

1
bjfletcher On BEST ANSWER

var balance = Some(0) is inferred to be of type Some[Int], when you need to tell this explicitly that it's of type Option[Int]:

var balance: Option[Int] = Some(0)

Then balance will be able to take in either Some(0) or None.

By the way, it's sometimes a good practice to always use Option(...) instead of Some(...). This is because Some(null) will become Some(null) whereas Option(null) will become None which is what we usually want.