Home > database >  Scala - meaning of "companion contains its own main method, which means no static forwarder can
Scala - meaning of "companion contains its own main method, which means no static forwarder can

Time:03-11

Given the following class and its companion object:

class B extends A

object B extends B

Where A is an abstract class in another file:

abstract class A { 
    def main(args: Array[String]): Unit = println("hey")
}

The above code is packaged into an uber-jar using the sbt assembly plugin, where the entry point is object B main method inherited from class B.

The above works fine. It runs. No problem at all.

Hoewver, sbt keeps warning:

[warn] B has the main method with parameter type Array[String], but B will not be a runnable program.
[warn]   Reason: companion contains its own main method, which means no static forwarder can be generated.
[warn] object B extends B
  1. Do you know the meaning of this warning?
  2. And why sbt assurance that object B won't run, doesn't happen?

Thank you.

CodePudding user response:

For a class to be runnable in java, main needs to be static. Yours isn't, so, the object isn't runnable. That's what compiler is telling you.

Just rename main in A to something else, and then add a main in the object, that calls it.

CodePudding user response:

It does not run for me.

I have this file B.scala.

package foo.bar

abstract class A {
    def main(args: Array[String]): Unit = println("hey")
}

class B extends A

object B extends B

When I try to run foo.bar.B I get an error:

sbt> runMain foo.bar.B
[info] running foo.bar.B
[error] (run-main-0) java.lang.NoSuchMethodException: foo.bar.B.main is not static

And the reason is exactly as the warning says. Class B contains a non-static main method which it inherited from class A. You can't have 2 methods with exactly the same name and type signature in one class, even if one is static and another in non-static. This means that the compiler cannot generate a static main method in class B that forwards to the non-static main method in object B.

Why it does run correctly for you I don't know.

  • Related