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
What I'm doing wrong?
A companion object is an object that's declared in the same file as a class , and has the same name as the class. A companion object and its class can access each other's private members. A companion object's apply method lets you create new instances of a class without using the new keyword.
To create a companion object, you need to add the companion keyword in front of the object declaration. The output of the above code is “ You are calling me :) ” This is all about the companion object in Kotlin. Hope you liked the blog and will use the concept of companion in your Android application.
If we declare the object inside a class, we have an option to mark it as a companion object. In terms of Java, the members of the companion object can be accessed as static members of the class. Marking an object as a companion allows us to omit the object's name while calling its members.
Companion object is known as an object whose name is same as the name of the class. Or In other words, when an object and a class have the same name, then that object is known as the companion object and the class is known as companion class.
You are trying to call the method getTag
in object EFCriteriaType
. There is no such method in that object. You could do something like:
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 secret
is accessible from Foo
's companion object. Bar will not compile since secret is inaccessible.
I'm not quite sure what you're trying to do here, but you need to call getTag on an instance of the class:
override def toString(x:EFCriteriaType) = x.getTag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With