Можно ли перегружать операторы в сопутствующих объектах Scala? - PullRequest
0 голосов
/ 06 октября 2019

Я бы хотел перегрузить операторы в сопутствующем объекте Scala. Возможно ли что-то подобное?

case class Complex(real: Double, imaginary: Double)

object Complex {
  def +(c1: Complex, c2: Complex): Complex = Complex(c1.real + c2.real, c1.imaginary + c2.imaginary)
  def add(c1: Complex, c2: Complex): Complex = c1 + c2
}

Выше приведено сообщение об ошибке метода add, говорящее Cannot resolve symbol +.

1 Ответ

3 голосов
/ 06 октября 2019

Попробуйте определить методы внутри класса дела

case class Complex(real: Double, imaginary: Double) {
  def +(c2: Complex): Complex = Complex(real + c2.real, imaginary + c2.imaginary)
  def add(c2: Complex): Complex = this + c2
}

или определить методы расширения, если у вас нет доступа к классу дела

case class Complex(real: Double, imaginary: Double) 

implicit class ComplexOps(c1: Complex) {
  def +(c2: Complex): Complex = Complex(c1.real + c2.real, c1.imaginary + c2.imaginary)
  def add(c2: Complex): Complex = c1 + c2
}

или исправить метод add вобъект

case class Complex(real: Double, imaginary: Double) 

object Complex {
  def +(c1: Complex, c2: Complex): Complex = Complex(c1.real + c2.real, c1.imaginary + c2.imaginary)
  def add(c1: Complex, c2: Complex): Complex = Complex.+(c1, c2)
}
...