WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Scala Β· Intermediate Β· question 33 of 100

How does Scala handle operator overloading? Provide an example.?

πŸ“• Buy this interview preparation book: 100 Scala questions & answers β€” PDF + EPUB for $5

In Scala, operator overloading is simply a matter of defining methods with the names of the desired operators. Unlike some other programming languages, in Scala, you can use symbols, such as β€˜+β€˜, β€˜-β€˜, β€˜*β€˜, and others as method names. These methods can then be called using infix notation, which looks like the operator is being used between two operands. Keep in mind that Scala actually does not have special syntax for operators but treats them like regular methods.

Here’s an example. Let’s create a simple β€˜Complexβ€˜ class representing complex numbers, and overload the β€˜+β€˜ and β€˜*β€˜ operators for adding and multiplying complex numbers.

class Complex(val real: Double, val imag: Double) {
  def +(other: Complex): Complex = {
    new Complex(real + other.real, imag + other.imag)
  }

  def *(other: Complex): Complex = {
    new Complex(
      real * other.real - imag * other.imag,
      real * other.imag + imag * other.real)
  }

  override def toString: String = s"($real + ${imag}i)"
}

Here we define a β€˜Complexβ€˜ class with two methods β€˜+β€˜ and β€˜*β€˜. Each method expects another β€˜Complexβ€˜ object as an argument and returns a new β€˜Complexβ€˜ object resulting from the addition or multiplication.

Now, we can create complex numbers and use the overloaded operators:

val c1 = new Complex(3, 4)
val c2 = new Complex(1, -1)

val c3 = c1 + c2
val c4 = c1 * c2

println(c3) // (4.0 + 3.0i)
println(c4) // (7.0 + 1.0i)

Here, we create two complex numbers β€˜c1β€˜ and β€˜c2β€˜, and then add and multiply them using the methods β€˜+β€˜ and β€˜*β€˜ using infix notation. The code β€˜c1 + c2β€˜ is actually calling the β€˜+β€˜ method on β€˜c1β€˜ with β€˜c2β€˜ as an argument. This also applies to β€˜c1 * c2β€˜, which calls the β€˜*β€˜ method on β€˜c1β€˜ with β€˜c2β€˜ as an argument. The results are printed as expected.

Note that when defining methods with symbolic names, you should be careful to balance the needs of readability and expressivity in your code. Using too many custom operators might make your code difficult to understand for other developers.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview β€” then scores it.
πŸ“ž Practice Scala β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Scala questions & answers β€” PDF + EPUB for $5

All 100 Scala questions Β· All topics