method name qualification when using a companion object

给你一囗甜甜゛ 提交于 2019-12-11 18:36:38

问题


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.


回答1:


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).




回答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.



来源:https://stackoverflow.com/questions/12231702/method-name-qualification-when-using-a-companion-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!