【问题标题】:Why is my companion object cannot access method in its companion class为什么我的伴生对象无法访问其伴生类中的方法
【发布时间】:2013-09-05 19:28:10
【问题描述】:

我是 Scala 新手。我读到伴生对象可以访问伴生类的方法。我有以下代码:

class MinPath {
  def minPath(input : List[List[Int]], tempResult : List[List[Int]], currentlevel : Int) : List[List[Int]] = {
    ....
  }
}

object MinPath {
  ....
  def main(args : Array[String]) = {
    // This has an compile error
    val transformed =  minPath(input, List(List()), 0)
  }
}

它们在同一个名为 MinPath.scala 的文件中定义。

但对象中使用的 minPath 会导致编译错误,因为它找不到 minPath。

我想知道我在这里做错了什么?

【问题讨论】:

  • Companion 对象不是类的实例,它就像一个具有静态方法/字段的类,如果您来自 Java 的话

标签: scala


【解决方案1】:

没有人提到这种常见的模式,它避免了创建一个无关的实例:

scala> :pa
// Entering paste mode (ctrl-D to finish)

class Foo {
  def foo= 8
}
object Foo extends Foo {
  def main(args : Array[String]) = {
    Console println foo
  }
}

// Exiting paste mode, now interpreting.

defined class Foo
defined object Foo

scala> Foo main null
8

显然,如果foo 是私有的,这也适用,这对我来说并不明显。也就是说,如果你扩展一个你有私有访问权限的类,那么其中的私有符号无需限定或导入即可访问。

scala> :pa
// Entering paste mode (ctrl-D to finish)

class Foo {
  private def foo= 8
}
object Foo extends Foo {
  def main(args : Array[String]) = {
    Console println foo
  }
}

// Exiting paste mode, now interpreting.

defined class Foo
defined object Foo

scala> Foo main null
8

【讨论】:

    【解决方案2】:

    main 方法中,您必须在MinPath 类的实例上调用minPath。所以你需要先创建一个实例:

    object MinPath {
      def main(args: Array[String]) {
        // Create an instance
        val instance = new MinPath
    
        // Call the method on the instance
        val transformed = instance.minPath(input, List(List()), 0)
      }
    }
    

    【讨论】:

      【解决方案3】:

      我读到伴生对象可以访问伴生类的方法。

      这意味着,如果minPath 被声明为protected 访问级别,object MinPath 仍然可以访问该方法。 scala 编译器不允许其他类访问它。

      目前,它具有默认的公共访问级别,因此访问级别不是这里的问题。

      正如 AlexIv 指出的那样,您还需要创建一个 class MinPath 的实例才能使用该方法。

      val mp = new MinPath
      val transformed = mp.minPath(input, List(List()), 0)
      

      【讨论】:

      • MinPath 是一个类,所以首先他应该实例化它然后调用/导入
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多