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.
var balance = Some(0)
is inferred to be of typeSome[Int]
, when you need to tell this explicitly that it's of typeOption[Int]
:Then
balance
will be able to take in eitherSome(0)
orNone
.By the way, it's sometimes a good practice to always use
Option(...)
instead ofSome(...)
. This is becauseSome(null)
will becomeSome(null)
whereasOption(null)
will becomeNone
which is what we usually want.