scala 无法从伴生对象访问伴生类的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11685718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:23:17  来源:igfitidea点击:

Can't access method of companion class from companion object

scalaobjectmethods

提问by GarfieldKlon

I thought that I can access every method of the companion class from my companion object. But I can't?

我以为我可以从我的伴生对象访问伴生类的每个方法。但我不能?

class EFCriteriaType(tag:String) extends CriteriaType
{
  // implemented method of CriteriaType
  def getTag = this.tag   
}

object EFCriteriaType
{
  var TEXT: CriteriaType = new EFCriteriaType("text")

  override def toString = getTag
}

Compiler error: not found: value getTag

编译器错误:未找到:值 getTag

What I'm doing wrong?

我做错了什么?

回答by Emil H

You are trying to call the method getTagin object EFCriteriaType. There is no such method in that object. You could do something like:

您正在尝试调用的方法getTagobject EFCriteriaType。该对象中没有这样的方法。你可以这样做:

object EFCriteriaType extends EFCriteriaType("text") {
  override def toString = getTag
}

Thus making the companion object a kind of template.

从而使伴生对象成为一种模板。

You can access members not normally accessible in a class from a companion object, but you still need to have an instance of the class to access them. E.g:

您可以从伴随对象访问类中通常无法访问的成员,但您仍然需要有一个类的实例来访问它们。例如:

class Foo {
  private def secret = "secret"
  def visible = "visible"
}
object Foo {
  def printSecret(f:Foo) = println(f.secret) // This compiles
}
object Bar {
  def printSecret(f:Foo) = println(f.secret) // This does not compile
}

Here the private method secretis accessible from Foo's companion object. Bar will not compile since secret is inaccessible.

这里的私有方法secret可以从Foo的伴生对象访问。Bar 不会编译,因为 secret 无法访问。

回答by Matthew Farwell

I'm not quite sure what you're trying to do here, but you need to call getTag on an instance of the class:

我不太确定您要在这里做什么,但是您需要在类的实例上调用 getTag:

override def toString(x:EFCriteriaType)  = x.getTag

回答by Edmondo1984

Just to detail Matthew answer, which is the right one:

只是为了详细说明马修的答案,这是正确的:

A companion object is a singleton but a class is not. a singleton. The companion object can access the methods of the class in the sense that a private member of the class C can be called in its companion object C.

伴生对象是单例,但类不是。单身人士。伴生对象可以访问类的方法,因为类 C 的私有成员可以在其伴生对象 C 中调用。

To call a member of a given class, you need an instance of that class (even if you are not doing that from a companion object)

要调用给定类的成员,您需要该类的一个实例(即使您不是从伴随对象执行此操作)