I am new to Scala. I read that the companion object can access companion class's method. I have the following code:
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)
}
}
They are defined in the same file called MinPath.scala.
But the minPath used in the object causes an compile error as it cannot find the minPath.
I am wondering what did I do wrong here?
No one mentioned this common pattern, which obviates creating an extraneous instance:
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
Apparently, that also works if foo
is private, which was not obvious to me. That is, if you extend a class to which you have private access, private symbols therein are accessible without qualification or import.
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
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