How can we implement arithmetic operations in Scala?
In Scala, addition, subtraction, multiplication, and division can be implemented using either operators or functions. Here are some common implementation methods:
- Utilizing operators:
- Addition: Using the “+” operator
val result = a + b - Subtraction: Using the “-” operator
val result = a – b - Multiplication: Use the “*” operator
val result = a * b - Division: use the “/” operator
val result = a / b
- Use functions:
- Addition: Using the “add” function
def add(a: Int, b: Int): Int = a + b
val result = add(a, b) - Subtraction: using the “subtract” function
def subtract(a: Int, b: Int): Int = a – b
val result = subtract(a, b) - Multiplication: Use the “multiply” function
def multiply(a: Int, b: Int): Int = a * b
val result = multiply(a, b) - Division: Use the “divide” function
def divide(a: Int, b: Int): Double = a.toDouble / b.toDouble
val result = divide(a, b)
Note: in the example code above, “a” and “b” represent two integers or floating point numbers, choose the appropriate data type based on the actual situation.