Unable to access companion class method from companion object

I thought that I could access each method of the companion object class from my companion object. But I can not?

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: getTag Value

What am I doing wrong?

+6
source share
3 answers

You are trying to call the getTag method on object EFCriteriaType . There is no such method in this object. You can do something like:

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

Thus, creating a companion object is a kind of template.

You can access members that are not normally available in the class from a companion object, but you still need to have an instance of the class to access them. For instance:

 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 secret method is accessible from the Foo of the companion object. The bar will not compile because the secret is not available.

+6
source

I'm not quite sure what you are trying to do here, but you need to call getTag for the class instance:

 override def toString(x:EFCriteriaType) = x.getTag 
+4
source

Just to answer Matthew's question, which is correct:

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

To call a member of this class, you need an instance of this class (even if you do not do this from a companion object)

+1
source

Source: https://habr.com/ru/post/921471/


All Articles