gpt4 book ai didi

scala - 为什么我的伴生对象无法访问其伴生类中的方法

转载 作者:行者123 更新时间:2023-12-01 09:00:10 30 4
gpt4 key购买 nike

我是 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。

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

最佳答案

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

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 是私有(private)的,这也适用,这对我来说并不明显。也就是说,如果你扩展了一个你拥有私有(private)访问权限的类,那么其中的私有(private)符号无需限定或导入即可访问。

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

关于scala - 为什么我的伴生对象无法访问其伴生类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18644404/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com