Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my companion object cannot access method in its companion class

Tags:

scala

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?

like image 789
Kevin Avatar asked Oct 12 '25 01:10

Kevin


1 Answers

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
like image 196
som-snytt Avatar answered Oct 15 '25 00:10

som-snytt