伴生对象方法只能在伴生对象中被调用,而不能在伴生类实例中被调用。如果需要使用伴生对象方法,可以通过伴生对象名称来调用:
class MyClass {
def someMethod(): Unit = {
// get the companion object and call its method
MyClass.companionMethod()
}
}
object MyClass {
def companionMethod(): Unit = {
// do something here
}
}
在伴生类中,我们可以使用 MyClass.companionMethod()
来调用伴生对象方法,从而避免了“Companion object method not available to the companion class instance”的问题。
上一篇:伴生对象的方法无法从子类访问