In this example we will create a simple application that allows users to interactively deposit and withdraw money from a bank account.
In Eclipse create a new Scala project called atm. Eclipse automatically generates a package called atm.
From the atm/src/atm shortcut menu, add a new Scala object named atm. Check the box asking if you want a main procedure automatically generated:
Eclipse generates a file called atm.scala containing the following code:
package atm
object atm {
def
main(args: Array[String]): Unit = {}
}
In Scala, like JavaScript, we can declare objects without instantiating a class. Object declarations are similar to class declarations except a singleton object is created.
An object declaring a main method as above is called an App object. From the Run/Run As/ Scala Application menu we can execute atm.main.
Here's atm.scala. Pay particular attention to the way errors are handled. Low level functions like deposit and withdraw throw specific types of exceptions indicating exactly what went wrong. The high level user interface (our repl function in this case) can catch all or some of these exceptions and handle them in different ways or it can simply catch the more general ATMException, handling all errors the same way, or it can ignore everything and let Scala handle the exceptions.
Here's a sample session:
-> deposit
amount = $100
balance = $100.0
...
-> withdraw
amount = $200
Insufficient funds
...
-> deposit
amount = $-200
amount must be positive
...
-> withdraw
amount = $fifty
amount must be a number
...
-> give me money
Invalid command, type help
...
-> help
Valid commands: withdraw, deposit, quit, and help
...
-> quit
...
bye
Define exception classes