Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Scala program to implement a Calculator operations.
Let’s look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.clearurdoubt class Calculator { def +(a: Int, b: Int): Int = a+b def -(a: Int, b: Int): Int = a-b def *(a: Int, b: Int): Long = a*b def /(a: Int, b: Int): Int = { require(b != 0, "denominator can not be 0") a/b } } object Calendar { def main(args: Array[String]) = { val calc = new Calculator() println("Addition: " + calc.+(10, 2)) println("Subtraction: " + calc.-(10, 2)) println("Multiplication: " + calc.*(10, 2)) println("Division: " + calc./(10, 2)) //println("Division: " + calc./(10, 0)) } } |
Output:
- We have created a Calculator class with 4 typical calculator methods +(addition), -(subtraction), *(multiplication) and /(division) methods. “+”, “-“, “*” and “/” are legal identifiers in Scala so we can have them as function names for better readability.
- We have named both the class and object names as “Calculator” and it is perfectly acceptable in Scala. These are called Companion objects/classes.
- require() is used to make sure a variable satisfies the provided condition to proceed further. If the condition fails(uncomment the line 29), the compiler will throw an exception, as below, with the message passed in the require():
- All the functions are returning some value in the above program but we haven’t specified “return” statement in any of them because “return” statement is optional in Scala.
Happy Learning :).
Please leave a reply in case of any queries.
Useful input is used to get the successful output… Loved the work…
Thank you Aditya 🙂