0

I am just learning Scala. I created a companion object (see code snippet below) where I define an operator, ^, (to represent complex conjugation). I have to qualify it with the companion objects name inside the associated class. I was under the impression that I should have unqualified access to the methods of the companion. Can someone tell me if I have done something wrong?

class CQ(val r: Q, val i:Q) {

  def +(z : CQ): CQ = {
    return new CQ(r + z.r, i + z.i)
  }

  def -(z: CQ): CQ = {
    return new CQ(r - z.r, i-z.i)
  }

  def *(z: CQ): CQ = {
    return new CQ(r*z.r - i*z.i, r*z.i + i*z.r)
  }

  def /(z: CQ): CQ = {
    val d = z.r * z.r + z.i * z.i
    val n = this * CQ.^(z) // that I needed to qualify "^" is what I don't get
    return new CQ(n.r / d, n.i /d)
  }

  override def toString = r + " + " + i + "i"
}
object CQ {

  def ^(z : CQ) : CQ = {
    return new CQ(z.r, Q.NEGONE*z.i)
  }

  val ONE = new CQ(Q.ONE,Q.ZERO)
  val ZERO = new CQ(Q.ZERO, Q.ZERO)
  val I = new CQ(Q.ZERO, Q.ONE)
  val NEGONE = I * I
}

NOTE: there is another class, Q, that is being used here but is not listed.

kiritsuku
  • 52,967
  • 18
  • 114
  • 136

2 Answers2

4

The members of the object and the class are in different scopes and are not imported automatically into the companion. So yes, you either need to use qualified access or import the member you need.

You might be confusing this with private access: you can access the private members of the companion (but only by qualified access or after importing).

Szabolcs Berecz
  • 4,081
  • 1
  • 22
  • 21
2

You need to import the function so that it is in scope:

import CQ.^

or, to import everything from the companion object:

import CQ._

An example:

class A(x: Int) {
  import A.^
  def f(y: Int) = x * ^(y)
}
object A {
  def ^(a: Int) = a - 1
}

println(new A(4).f(3))

The import line can be either inside or outside the class definition, depending on your preference.

dhg
  • 52,383
  • 8
  • 123
  • 144